We now have a youtube channel. Subscribe!

Express.js | Routing

Express.js | Routing


Hello folks! Welcome back to a new edition of our tutorial on ExpressJS. In this tutorial, we're going to be studying about Express.js Routing.

Web framewoks makes available resources like HTML pages, scripts, images, and so on at different routes.

The following function defines routes in an Express application -

app.method(path, handler)

This method can be used on anyone of the HTTP verbs - get, set, put, options, post. An alternate method also exist, which executes independent of the request type.

Parameter Details

Path is the route upon which the request will run.

Handler is a callback function that executes when a matching request type is discovered on the relevant route. For example,

var express = require('express');
var app = express();

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.listen(3000);

If we run our application and go to the path localhost:3000/hello, the server receives a get request at path "/hello", our Express app executes the callback function attached to this route and sends back "Hello World!" as the response.

routing_hello(1)


We can also have numerous methods at the same route. For example,

var express = require('express');
var app = express();

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.post('/hello', function(req, res){
   res.send("You just called the post method at '/hello'!\n");
});

app.listen(3000);

To test this request, open your terminal and use cURL to execute the following request -

curl -X POST "http://localhost:3000/hello"

routing_curl

A special method, all, is made available by Express to handle all types of http methods at a given route using the same function. To use this method, try the following code.

app.all('/test', function(req, res){
   res.send("HTTP method doesn't have any effect on this route!");
});

This method is generally used for defining middleware, which we are going to discuss in the middleware tutorial.

Routers

Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we'll use Express.Router. Create a new file called things.js and input the following in it.

var express = require('express');
var router = express.Router();

router.get('/', function(req, res){
   res.send('GET route on things.');
});
router.post('/', function(req, res){
   res.send('POST route on things.');
});

//export this router to use in our index.js
module.exports = router;

Now to use this router in our index.js, input the following before the app.listen function call.

var express = require('Express');
var app = express();

var things = require('./things.js');

//both index.js and things.js should be in same directory
app.use('/things', things);

app.listen(3000);

The app.use function call on route '/things' attaches the things router with this route. Now whatever requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js is actually a subroute of '/things'.

Output

Visit localhost:3000/things/ and you will see the following output -

router_things

Routers are helpful in separating concerns and keeping relevant portions of our code together. They help in building maintainable code. You should define your routes relating to an entity in a single file and add it using the above method in your index.js file.


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about Express.js HTTP Methods.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain