Nodejs(Express框架):无法将数字API从外部服务器打印到客户端浏览器



我正在尝试从外部服务器检索weather API,当我在控制台记录weather API的特定数据时,它也会显示在我的命令提示符上。但当我使用get方法在浏览器上显示数据时,我只能发送字符串数据,如";描述":中雨,而不是像";temp":27它使应用程序崩溃。

节点js代码:

//jshint esversion:6
const express = require("express");
const app = express();
const https = require("https");

app.get("/", function(req, res) {

const url = "https://api.openweathermap.org/data/2.5/weather?q=mumbai&appid=d88391210768983e6be06cdd76bdcde3&units=metric";
https.get(url, function(response) {
console.log(response.statusCode);
response.on("data", function(data) {
const weatherData = JSON.parse(data);
const temp= weatherData.main.temp;
const description= weatherData.weather[0].description;
console.log(temp);
console.log(description);
res.send(temp);
});
});
});

app.listen(3000, function() {
console.log("Server is running on port: 3000");
});

理想情况下,您应该返回一个json。它可以是:

res.send({temp: temp, description: description});

res.send必须返回一个字符串/对象/数组/缓冲区
您可以执行以下操作:

res.status(200).send(temp)

但是发送json响应更可取,而且您也可以扩展它。

另一种破解类型的解决方案是:

res.send("" + temp)

最新更新