skip to Main Content
`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={apikey}&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

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search