Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
In this video I'll show you how I parsed the data and printed in to the console.
Documentation
OpenWeatherMap API Solution Code
Here's an overview of the differences from the code shown in the video:
-
weather.js
- The data object returned from the API uses a different structure, so the
printWeather()
function needed to be tweaked
- The data object returned from the API uses a different structure, so the
Here's the code:
weather.js
const https = require('https');
const querystring = require('querystring');
const api = require('./api.json');
// Print out temp details
function printWeather(weather) {
const message = `Current temperature in ${weather.name} is ${weather.main.temp}F`;
console.log(message);
}
// Print out error message
function get(query) {
//const url = `https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json`;
const parameters = {
APPID: api.key,
units: 'imperial'
};
const zipCode = parseInt(query);
if (!isNaN(zipCode)) {
parameters.zip = zipCode + ',us';
} else {
parameters.q = query + ',us';
}
const url = `https://api.openweathermap.org/data/2.5/weather?${querystring.stringify(parameters)}`;
console.log(url);
const request = https.get(url, response => {
let body = '';
// Read the data
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
//Parse data
const weather = JSON.parse(body);
//Print the data
printWeather(weather);
});
});
}
module.exports.get = get;
//TODO: Handle any errors
At the top of the weather.js file,
I've implemented a printWeather function
0:00
that takes in a JSON object returned
from the API and prints out this city,
0:06
And the temperature in Fahrenheit.
0:14
The reason I'm getting the city from the
location, rather than the query inputted
0:17
by the user, is that if a user
is to put in a zip code and
0:21
made a slight error with one of the
numbers, at least they'll see an easily
0:26
understandable location to
help spot their mistake.
0:30
Finally, down in the response,
where the end event handler is,
0:36
we're parsing the JSON here and
printing out the weather location.
0:41
Let's see the output in action.
0:48
Node app.js 90210.
0:53
Awesome, your next challenge is to handle
any connection parsing status code and
1:00
any other errors that your
program might encounter.
1:06
Good luck, and I'll share with you
my solution in the next video.
1:11
You need to sign up for Treehouse in order to download course files.
Sign up