【问题标题】:can't receive response from OpenWeatherMap API at all根本无法收到来自 OpenWeatherMap API 的响应
【发布时间】:2021-07-05 16:43:28
【问题描述】:

我是后端编程的新手,最近我遇到了无法从 Open Map Weather API 接收任何数据的问题...我正在尝试使用 node.js 中的 https/express 发送我的请求... 我的 API 密钥和所有参数都是正确的,因为在 Postman 中一切正常...... 如果有人能帮我解决这个问题,我将不胜感激...... - 这是我的代码 btw-

const exp = require("express");
const hhh = require("https");
const app = exp();
app.get("/", (req, res) => {

    const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=249e0887318ca2b591a7911fd54fe5fe";
    hhh.get(url, (response) => {
        console.log(response);
    })

    res.send("<h1>On Air 3000</h1>")
})


app.listen(3000, () => {
    console.log("Listening on 3000");
})    

【问题讨论】:

    标签: node.js api express visual-studio-code hyperterminal


    【解决方案1】:

    来自官方文档[这里]:https://nodejs.org/api/http.html#http_http_get_options_callback.

    使用一个作为 http.IncomingMessage 实例的参数调用回调。

    所以response 是 http.IncomingMessage 类的一个对象,它允许您从 API 获取响应,而不是您在浏览器或 Postman 中看到的结果。您可以从上面的同一文档中看到一些代码示例。

    对于你的情况,你可以检查下面的代码,我测试过,它有效:)

    const exp = require("express");
    const hhh = require("https");
    const app = exp();
    app.get("/", (req, res) => {
    
        const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=249e0887318ca2b591a7911fd54fe5fe";
        hhh.get(url, (response) => {
    
            var result = '';
    
            //data come by chunks, we append new chunk to result
            response.on('data', function (chunk) {
              result += chunk;
            });
          
            //when we receive all the data, print to screen
            response.on('end', function () {
              console.log(result);
            });
        })
    
        res.send("<h1>On Air 3000</h1>")
    })
    
    
    app.listen(3000, () => {
        console.log("Listening on 3000");
    })
    

    【讨论】:

      猜你喜欢
      • 2014-10-24
      • 2013-05-13
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2020-12-10
      相关资源
      最近更新 更多