Creating a simple website that shows Guarda’s temperature

Cris Ferreira Pires
4 min readMar 17, 2021

--

After being asked to make some exercises about APIs on a Distributed Systems class.

I went a bit further than what was asked. And ended up making a simple page with all the ground work to make a complete website for the meteorology of a certain city, all it needs is some html/css work.

So for starters we need to set up the web server, for that we create a file, here named main.js and add the following code.

const port = process.env.PORT || 8080; //Defines the port where the server will listen for requestsconst express = require('express'); //Web FrameWorkvar app  = express();
app.listen(port,()=> //Actually brings the server online
{
console.log('Server Up');
});

We will need to set two variables one is the city you will want to get the temperature, the other is the openweathermap api key. For this you will need to go to openweathermaps.org and create an account.

Then you should add the key to your environment variable but you can use it in plain text if you are just going to be testing on your machine.

const apiKey = process.env.OpenWeatherMapKey  || 'YOURKEY'; //API should be hidden in the ROOT PATH or in a dotEnv file. To do so remove the or and the string.const city= 'YOURCITY'; // Sets the city name that will be used when getting a new temperature.

This doesn’t yet do anything. For that we need to set routes, routes are what the final user would put at the end of the url. Since we don’t want to complicate we will set a route for the default ‘/’.

app.get('/', (req, res)=> //When a client asks for the page
{
//This is the middleware function.
res.render('index', (err, html)=>
{
//This is were we will code the middleware
});
})

This doesn’t show anything because we haven’t set the view engine for express, nor the view folder. So we need to do just that create a new folder and call it views on root (same “level” as the main.js file).

Then inside you create a file named index.ejs.

It doesn’t need to have much inside, just the following to make sure it everything works.

<!DOCTYPE html>
<body>
<p>test</p>
</body>
Also you need the ejs module. After oppening the terminal on the root folder you must write:

But the if you try to load the page it will give you an error. Thats because we haven’t set the view engine for expressjs yet . Before that we need to get the ejs module. And while we are at it we will actually download all the modules.

Opening a terminal on the root folder we will use this commands.

npm i -s expressnpm i -s ejsnpm i -s cheerionpm i -s request

After that we need to call them in our code.

const request = require('request'); //Makes client like requests to other web serversconst express = require('express'); //Web FrameWorkconst cheerio = require('cheerio') //Implementation of JQuery for html manipulation.const path = require('path'); //Path tool for joining default path with folders.

Now we can get the temperature from the api with request.

Request needs 1 parameter, it is the URL. This accesses a page as a client and gives back 3 variables, error if an error occurred, response whitch is the response state that the webserver is at, and body, the html that the client sees when accessing that page.

For this porpuse we will take the body variable and parse it to make it an object, as its normal type is string.

var url = `http://api.openweathermap.org/data/2.5/weather?q=${City}&appid=${apiKey}&units=metric`
request(url, (e, r, b)=> //requesting new temperature.
{
try
{
b = JSON.parse(b)
}
catch (e)
{
console.log(e);
}
});

Now we have a way to get the information and a page. Now is a question of how do you want to present it.

In this example we will use a simple html header with some text. You could make this in a different way to make this prettier.

We will use cheerio to add the html header.

var url = `http://api.openweathermap.org/data/2.5/weather?q=${City}&appid=${apiKey}&units=metric`
request(url, (e, r, b)=> //requesting new temperature.
{
const $ = cheerio.load(html);
try
{
$('body').append(`<h1> Temperatura na : ${City} é ${JSON.parse(b).main.temp}℃</h1>`); // Appending new temperature to the page's html.
res.send($.html()); //Actualy Serving the page.
}
catch (e)
{
console.log(e);
}
});

Then we do some simple error handling:

var url = `http://api.openweathermap.org/data/2.5/weather?q=${City}&appid=${apiKey}&units=metric`
request(url, (e, r, b)=> //requesting new temperature.
{
const $ = cheerio.load(html);
if(e) res.sendStatus(500); // Error status 500 - Internal Error
try
{
$('body').append(`<h1> Temperatura na : ${City} é ${JSON.parse(b).main.temp}℃</h1>`); // Appending new temperature to the page's html.
res.send($.html()); //Actualy Serving the page.
}
catch (e)
{
res.sendStatus(404) // Error status 500 - Internal Error
}
});

The final code will look something like this:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response