Home > Blockchain >  node js error Cannot read property 'temp' of undefined open weather api
node js error Cannot read property 'temp' of undefined open weather api

Time:01-31

`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");
});`

i am using open weather api and trying to log temprature in main object iam getting the error:-

const Temp = weatherData.main.temp;
                              ^

TypeError: Cannot read property 'temp' of undefined

also why does stack overflow makes it so hard to post questions

CodePudding user response:

I think the query is returning a different JSON than you're expecting, it seems like it returns an object with a list of temperatures at different times, not just one 'temp'. I recommend you downloading a JSON browser extension and looking at the JSON in the browser: https://api.openweathermap.org/data/2.5/forecast?q=delhi&appid=0e9bd132a69ddc33c030e2bda11ac71f&units=metric

CodePudding user response:

heres what i did

stored the list array is a variable tempList used [tempList.length -1] to get to get the last element of the list

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);
});
  • Related