【发布时间】:2020-07-09 09:23:42
【问题描述】:
希望您能帮帮我,我正在运行 Node.js 并尝试从 API 获取城市名称,但一直显示错误
说它无法读取未定义的属性city_name。
卡在代码的这一行:
const cityName = weatherData.data.city_name;
任何线索为什么这样做?请
// Creating the server of the weather app
const express = require('express');
const app = express();
const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');
const https = require('https');
app.get('/', (req, res) => {
const weatherPath = "https://api.weatherbit.io/v2.0/current?key=41c0f84d717a4764a26d144aa33a9443&city=melbourne,Australia"
// Calling the weather app
https.get(weatherPath, (response) => {
console.log(response.statusCode);
// Getting the data from the weather app
response.on('data', (d) => {
//console.log(d);
// Converting the buffer data from the weather app
console.log(decoder.write(d));
const weatherData = decoder.write(d);
const cityName = weatherData.data.city_name;
console.log(cityName);
});
});
res.send("The server is up and running on the web");
});
app.listen(3000, () =>
{
console.log('Server is running on port 3000');
});
【问题讨论】:
标签: node.js arrays json api get