json node js错误无法读取未定义的打开天气API的属性'temp'

nzrxty8p  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(67)
`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/forecast?             q=delhi&appid=0e9bd132a69ddc33c030e2bda11ac71f&units=metric";

  https.get(url, function (response) {
    console.log(response.statusCode);

    response.on("data", function(data){
      const weatherData = JSON.parse(data);
      console.log(weatherData);

      const Temp = weatherData.main.temp;
      console.log(Temp);
    });
  });
  res.send("server is up");
});

app.listen(3000, function () {
  console.log("server is running");
});`

我正在使用开放的天气API,并试图在主对象中记录温度iam得到错误:-

const Temp = weatherData.main.temp;
                              ^

TypeError: Cannot read property 'temp' of undefined

还有为什么栈溢出会使提问变得如此困难

kgsdhlau

kgsdhlau1#

我认为查询返回的JSON与您预期的不同,它似乎返回了一个包含不同时间的温度列表的对象,而不仅仅是一个“temp”。我建议您下载一个JSON浏览器扩展并查看浏览器中的JSON:https://api.openweathermap.org/data/2.5/forecast?q=delhi&appid=0e9bd132a69ddc33c030e2bda11ac71f&units=metric

42fyovps

42fyovps2#

这就是我所做的
存储列表数组的是变量tempList,使用[tempList.length -1]获取列表的最后一个元素

response.on("data", function(data){
  const weatherData = JSON.parse(data);
  var tempList = weatherData.list;
  const Temp = tempList[tempList.length -1].main.temp;
  console.log(Temp);
});

相关问题