JavaScript Node.js Basics Create a Command Line Weather Application Parsing Data and Printing - Solution

Nathaniel Evans
Nathaniel Evans
14,205 Points

Issue getting the correct parameters (I think)

Hello all,

I'm having an issue getting the correct parameters passing in my printWeather function for the Node.js challenge. The API I'm using to call the city name and weather ID is Open Weather Map - I'm using the docs found here: https://openweathermap.org/current#current_JSON

Currently, when running my code, I get the printWeather message "The temperature in undefined is undefined". I'm looking to have it return a message e.g. "The temperature in Toronto is 14 degrees C" or similar.

const https = require("https");
const http = require("http");

function printWeather(weather) {
    message = `The temperature in ${weather.name} is ${weather.main.temp}.`;
    console.log(message);
}

function getWeather(city) {
    const request = http.get(`http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=03d21c74966bde3f834a355c42432b86`, response => {
        let body = "";
        response.on("data", chunk => {
            body += chunk.toString();
        });
        response.on("end", () => {
            // console.log(body);
            //parse data
            const weather = JSON.parse(body);
            printWeather(weather);
            //print data
        });
    });
};

getWeather();

2 Answers

Tom Gooding
Tom Gooding
16,735 Points

Hi Nathaniel,

Your code works apart from the line below. You are just referencing the wrong path in the JSON response.

let message = `The temperature in ${weather.city.name} is ${weather.list[0].main.temp}.`;
// 0 index of weather.list being the most recent measurement

If you want to get the weather for a specific city you will need to pass the city through to the get request URL.

http://api.openweathermap.org/data/2.5/forecast?q={city_name}&APPID={APIKEY}

Nathaniel Evans
Nathaniel Evans
14,205 Points

Hi Tom,

Thanks so much for your answer, I appreciate it. :)