Making a meteorology app using Node.js and OpenWeatherMap API on MacOS
This tutorial will show you how to create simple weather app using node.js and OpenWeatherMap API.
Step 1- Create an account on the site OpenWeatherMap.
To get start we need to access the OpenWeatherMap website https://home.openweathermap.org/users/sign_up and register.
Then we select API Keys to create a key, to do this we have to insert in the name field a name that will be associated with the key that is generated.
Step2- Developing the app
If you already have Node.js configured, the first thing to do is to create a directory with the name nodejs-weather and then we open terminal and type the following command (after we change the directory):
npm init
Fill the fields with the information you want and press enter.
The output will be similar to the image below:
Then we type the following command to add the packages:
npm install request -save
We create a file with the name Index.js with the following code:
let request = require(‘request’);
let apiKey = ‘YOUR KEY’;
let cidade = ‘YOUR CITY’;
let url = `http://api.openweathermap.org/data/2.5/weather?q=${cidade}&appid=${apiKey}&units=metric`
request(url, function (err, response, body) {
if(err){
console.log(‘error:’, error);
} else {
let weather = JSON.parse(body)
let dados = `Dados da temperatura para ${weather.name}:
— Temperatura : ${weather.main.temp}ºC
— Humidade : ${weather.main.humidity} % `
console.log(dados);
}
});
Note that in the line 3 and 4 you type your Api Key and the city you want.
Finally on the terminal type the following command:
node index.js
The output will look like this: