【发布时间】:2022-01-10 11:49:08
【问题描述】:
Weather Data not printing in my command line
我尝试从 URL 打印如图所示的 weatherData,但它没有在控制台中打印出来。可能是什么问题,我该如何解决?
【问题讨论】:
标签: node.js api express command-line-interface node-modules
Weather Data not printing in my command line
我尝试从 URL 打印如图所示的 weatherData,但它没有在控制台中打印出来。可能是什么问题,我该如何解决?
【问题讨论】:
标签: node.js api express command-line-interface node-modules
您的代码有两个问题(除了它作为屏幕截图提供):
response 对象。data 事件只传递一个数据块;可能有多个,然后是 end 事件。https.get(url, function(response) {
console.log(response.statusCode);
var weatherData = "";
response.on("data", function(data) {
weatherData += data.toString();
}).on("end", function() {
console.log(JSON.parse(weatherData));
});
});
【讨论】:
到目前为止,最简单的下载方法是使用 Windows 原生 Curl 命令,您可以通过 Cmd 控制台窗口运行该命令,保存响应文件,然后查询该 response.txt
首先确认您的网址有效(点击下方链接)
如果您使用的是 Windows 10 或 11,您应该拥有 curl 的原生版本,只需在 cmd 行尝试此操作(注意您需要将 url 中的每个 & 用 ^ 转义像这样^&)或使用“URL”(如此完整的双“引号”),但在嵌套在shell命令时要小心。
curl -o response.txt https://api.openweathermap.org/data/2.5/weather?q=Paris^&appid=536bcef96b2f01cd9b9f076db90807fe^&unit=metric
type response.txt
您可以将两者都包含在一行中,但 &type 最后一个 & 不需要 ^escape
curl -o response.txt https://api.openweathermap.org/data/2.5/weather?q=Paris^&appid=536bcef96b2f01cd9b9f076db90807fe^&unit=metric&type response.txt
下载后,您应该会在控制台中看到 response.txt。
因此您可以以任何您希望的方式调用该命令(是否隐藏>nul),或者在屏幕上或您选择的任何应用程序中读取文本文件。
响应.txt
{"coord":{"lon":2.3488,"lat":48.8534},"weather":[{"id":804,"main":"Clouds","description":"阴云" ,"icon":"04n"}],"base":"stations","main":{"temp":277.1,"feels_like":277.1,"temp_min":275.8,"temp_max":278.23,"pressure ":1009,"湿度":98},"能见度":10000,"风":{"速度":1.03,"deg":0},"云":{"all":100},"dt" :1641768056,"sys":{"type":2,"id":2012208,"country":"FR","sunrise":1641714129,"sunset":1641744764},"timezone":3600,"id" :2988507,"名称":"巴黎","鳕鱼":200}
【讨论】: