How to create a weather app in nodejs
Nowadays there are many web services that provide the latest weather updates. Open Weather Map is a widely used API by developers. In this tutorial, you are going to create a weather app in NodeJS. A user enters a city name and clicks the Fetch Weather button, weather data returned from Open Weather API is displayed to the user.
Following tasks are performed in this tutorial
2. Generate a weather app in nodejs using express command line tool
3. Create an HTML form and a table to display data
4. Create a /weather route to fetch weather for a city
Register for Open Weather Map API
Visit Open Weather Map website and register an account.
Login to your account after account creation. Click on API Keys and you can view the API Key. Copy this API Key to use in weather app in nodejs.
You can view different price plans by visiting this link. In a free plan, there are following limits.
- Threshold: 7,200
- Hourly forecast: 5
- Daily forecast: 0
- Calls 1 min: 60
Using open weather map API you can get historical data, weather alerts, weather map layers, current weather data, the daily forecast for 16 days, and 3-hourly forecast or 5 days for your city.
Get city weather by name
To get a city weather, you can use the URL given below. The cityName and appid are used as placeholders.
http://api.openweathermap.org/data/2.5/weather?q=CityName&appid=YOUR_API_KEY
Cityname is replaced by user entered city name. Replace API KEY with your account’s API Key. If you access above URL in the browser and add city name as London.
Install NodeJS
To install NodeJS, download NodeJS from the download page and install. NPM or Node Package Manager is also installed with nodejs.
Install Express Generator tool
Express tool is also installed with the express generator installation. Express is used to generate a nodejs express app skeleton.
npm install express-generator -g
Generate weather app in nodejs using express
Open the command line and go to the directory where you want to create the project. Pug is used as a template engine.
express --view=pug weather-app-nodejs
Install dependencies and modules
Next, install the required dependencies
cd weather-app-nodejs && npm install
Install nodemon module
Normally, if you have a running app in nodejs and a change is made to the code files, the app needs to be restarted. nodemon is a module that monitors any change in files and automatically restarts the server.
npm i nodemon
Run the application
On the command line, type
nodemon
To view the running application, open browser, and type URL.
http://localhost:3000
Open the project in your favorite IDE like Atom, Sublime Text or Brackets. The project structure looks like.
Add bootstrap in layout.pug file
Open layout.pug file in views directory.
doctype html html(lang="en") head title Weather App in NodeJS meta(charset="utf-8") meta(name="viewport" content="width=device-width, initial-scale=1") link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css") script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js") script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js") body block content
Below body tag, a block named content is added.
Create a form in index.pug file
Open index.pug file and add the code.
extends layout block content .container h2 p | Weather App in NodeJS using Open Weather API br br .row .col-md-6 form.form-inline(method="post", action="weather") .form-group label.sr-only(for="inputEmail") City Name input.form-control( name="city" type="text" placeholder="Enter City Name" required='required') | button.btn.btn-primary(type="submit") Fetch Weather hr
After the extends layout command a form is created. HTTP POST method is used to send the data to the server. Action parameter is set to weather route. A text input named city with a submit button is added.
Add an HTML table to display records
Add a table below the form.
.row .col-md-12 p br br strong Weather Forecast #{forecast} table.table thead tr th Longitude / Latitude th Pressure th Temprature th Humidty th Speed tbody if body tr td #{body.coord.lon} / #{body.coord.lon} td #{body.main.pressure} td #{body.main.temp} td #{body.main.humidity} td #{body.wind.speed} else tr td(colspan="6") | Enter city name and click Fetch Weather button
In table header, longitude/latitude, pressure, temperature, humidity and speed are added. If the body array has data then coordinates, pressure, temperature, humidity, and speed data is displayed.
Install request module in weather app in nodejs
To send a request to open weather map API, request module is installed.
npm i request --save
Add API credentials in index.js
Open index.js in routes directory. A URL variable is created that points to open weather map’s API. Notice an URL parameter ?q=. The value after param q is appended after the user’s input. Add your account’s API Key in appid variable. Units are used as metric.
let url = 'http://api.openweathermap.org/data/2.5/weather?q=' let appId = 'appid=YOUR API KEY'; let units = '&units=metric'; var request = require('request');
Update index route
Replace the code in ‘/’ route in index.js. Empty body and, forecast variables assigned to the template.
/* GET home page. */ router.get('/', function(req, res, next) { res.render('index', {'body':'', forecast: ''}); });
Create the Weather route
Open index.js in routes folder.
router.post('/weather', function(req, res, next){ let city = req.body.city; url = url+city+"&"+appId; request(url, function (error, response, body) { body = JSON.parse(body); if(error && response.statusCode != 200){ throw error; } let country = (body.sys.country) ? body.sys.country : '' ; let forecast = "For city "+city+', country '+country; res.render('index', {body : body, forecast: forecast}); }); });
Form data is posted to this route. The city name is assigned to the city variable using Nodejs’s request object. URL is appended with city name and appID. Using request method to the URL, a request is sent to open weather map API.
This method returns the error, response and body parameters in the callback method. An error is thrown if an error is returned. Body parameter is returned as a JSON. JSON data is parsed. Forecast variable, created with country and city variable name and body variable is assigned to the template.
If you console.log the JSON data returned from open weather map API on the server.
Search for Toronto’s weather
{ "coord":{ "lon":-79.39, "lat":43.65 }, "weather":[ { "id":800, "main":"Clear", "description":"clear sky", "icon":"01d" } ], "base":"stations", "main":{ "temp":297.7, "pressure":1022, "humidity":83, "temp_min":297.05, "temp_max":298.15 }, "visibility":14484, "wind":{ "speed":2.1, "deg":180 }, "clouds":{ "all":1 }, "dt":1537020000, "sys":{ "type":1, "id":3721, "message":0.0029, "country":"CA", "sunrise":1537009056, "sunset":1537053998 }, "id":6167865, "name":"Toronto", "cod":200 }
The JSON data contains coordinates, weather, temperature, and other information.
Search for London weather in weather app in nodejs
If the app is still running, enter London as city and click fetch weather button. Weather data such as longitude, latitude, pressure, temperature, humidity, and speed is displayed.
Search for New York’s weather in weather app in nodejs
If user searches for New York City weather.
Summary
To summarize, in this tutorial on creating a weather app in nodejs, an account is registered on Open weather map. A nodejs app is generated and a form with an HTML table is created. When the user enters the name of a city, a request is sent to Open Weather API. JSON data is sent back to the server and is displayed to the user.
You can clone or download the source code for this tutorial from this GitHub repository.
Leave your valuable feedback. To stay updated on upcoming articles and tutorials, follow us on twitter, like us on Facebook or subscribe to our newsletter.
Related Articles
- NodeJS MongoDB RESTful API
- NodeJs MongoDB Tutorial
- Nodejs File Upload With MongoDB – Photo Gallery
- NodeJs user registration tutorial
- Using socketio with nodejs
Previous Articles
Next Article