Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Node.js Basics 2017 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. :)