Node.js: Requisitions with the base on the URL on http and Express.js

NSerus
2 min readMar 22, 2021

We already seen how it is easy to create an HTTP server in the end of my first tutorial.

Today we are going to see how Node.js responds requisitions with the base on the URL.

Let’s consider 3 categories for your server:

  • Express
  • Node
  • OWM

The JavaScript code to implement a service that satisfies our needs would be:

var http = require('http');

var server = http.createServer(function(req, res) {
var cat = req.url; //gets the url
switch(cat){
case '/exp':
res.end('Express'); //reponds
break;
case '/node':
res.end('Node'); //reponds
break;
case '/owm':
res.end('Open Weather Maps'); //reponds
break;
default:
res.end('Welcome to nothin'); //reponds
break;
}
}).listen(8080);

But there is a simpler way to develop Web Apps…

Express.js

A back end Web Application Framework for Node.js, calles the de facto Standard server framework for Node.js.

You need to install it using npm , you need to run this command in the project’s directory every time you want to start a new project to transfer all the needed files for Express.js to run properly:

npm install express -save

Refactoring the code for Express.js will look like this:

var express = require('express'); //nova funcionalidade expressvar app = express();

app.get('/',function(req,res){
res.send("Welcome to nothin");
});
app.get('/exp',function(req,res){
res.send("Express");
});
app.get('/node',function(req,res){
res.send("Node");
});
app.get('/owm',function(req,res){
res.send("Open Weather Maps");
});
app.listen(8080,function(){
console.log("Servidor ativo no porto 8080");
});

And now, executing the code, since in the “Express” way and the “http” way execute the same way there is no need to show both executions of code or outputs.

Execution (FOR EXPRESS OR HTTP)

And you can execute it in the directory with the normal…

node index.js

You can now test the results on the browser:

The Default route:

Default

The /owm route:

/owm route

The /node route:

/node route

The /exp route:

/exp route

--

--