问题描述
我是后端编程的新手,最近我遇到了无法从 Open Map Weather API 接收任何数据的问题...我正在尝试在 node.js 中使用 https/express 发送我的请求... 我的 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) => {
console.log(response);
})
res.send("<h1>On Air 3000</h1>")
})
app.listen(3000,() => {
console.log("Listening on 3000");
})
解决方法
来自官方文档[这里]: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");
})