Node.js 尝试从open weather api获取某些数据时出错
此应用程序通过api,app.js从开放天气图中获取小段数据:Node.js 尝试从open weather api获取某些数据时出错,node.js,express,Node.js,Express,此应用程序通过api,app.js从开放天气图中获取小段数据: const express = require("express"); const https = require('https'); const app = express(); app.get("/", function (req, res) { const url = "https://api.openweathermap.org/data/2.5/weather?q=
const express = require("express");
const https = require('https');
const app = express();
app.get("/", function (req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=Khartoum&appid=d244334364579178494bb3c4528e218b&units=metric"
https.get(url, function (response) {
response.on("data", function (data) {
const weatherData = JSON.parse(data);
res.write(weatherData.weather[0].description);
res.write(weatherData.weather[0].id);
res.send();
});
});
});
app.listen("3000", function () {
console.log("runnign on port 3000.");
});
重新加载页面时在终端中触发的错误:
_http_outgoing.js:671
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received type number (804)
at write_ (_http_outgoing.js:671:11)
at ServerResponse.write (_http_outgoing.js:636:15)
at IncomingMessage.<anonymous> (/home/foola/Desktop/appBrewery/WeatherProject/app.js:18:17)
at IncomingMessage.emit (events.js:315:20)
at IncomingMessage.Readable.read (_stream_readable.js:512:10)
at flow (_stream_readable.js:985:34)
at resume_ (_stream_readable.js:966:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_INVALID_ARG_TYPE'
\u http\u outgoing.js:671
抛出新错误\u无效的\u参数\u类型('第一个参数',
^
TypeError[ERR_INVALID_ARG_TYPE]:第一个参数的类型必须是string或Buffer的实例。收到的类型号(804)
在写入时(_http_outgoing.js:671:11)
在ServerResponse.write(_http_outgoing.js:636:15)
在IncomingMessage上。(/home/douga/Desktop/appBrewery/WeatherProject/app.js:18:17)
在IncomingMessage.emit(events.js:315:20)
在IncomingMessage.Readable.read(_stream_Readable.js:512:10)
流动时(_stream_readable.js:985:34)
在resume上(_stream_readable.js:966:3)
在处理和拒绝时(内部/process/task_queues.js:84:21){
代码:“错误\无效\参数\类型”
那么这里到底出了什么问题?mybe
weatherData.weather[0].id
是一个类似整数的数字类型吗?
试一试
mybe
weatherData.weather[0].id
是一个类似整数的数字类型吗?
试一试
如错误消息所示,
res.write
仅接受缓冲区或字符串,weatherData.weather[0].id
的类型为int/number,因此您可能希望在将其传递给res.write
之前先对其进行字符串化
res.write(weatherData.weather[0].id.toString())
如错误消息所示,
res.write
仅接受缓冲区或字符串,weatherData.weather[0].id
的类型为int/number,因此您可能希望在将其传递给res.write
之前先对其进行字符串化
res.write(weatherData.weather[0].id.toString())