At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

Routing in Node.js tutorial with specific examples

  • By Annamalai
  • August 20, 2019
  • 26427 Views

What is routing?

To start with routing in Node.js, one needs to know what is routing and its purpose. The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern. 
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Node.js represents a “JavaScript everywhere” paradigm, unifying web application development around a single programming language, rather than different languages for server- and client-side scripts. One can even develop an API in 30 minutes with Node.js!

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications and hence we are using it as our base for this blog page. 

Basics to Route Creation

A route method is derived from one of the following HTTP methods, and is attached to an instance of the express class as below :

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

.get() – Used to get data from a URL.
.put() – Used to update data.
.post() – Used for posting data to server / application. Normally it’s used while form submit.
.delete() – as the name explains, this method is used to delete data.
.all() – A special routing method which supports all the above. This can be used to run middleware functions, like authentication, validation for all HTTP requests. Each route can have one or more handler functions, which are executed when the route is matched.
Route Definition
It takes the following structure:

app.METHOD(PATH, HANDLER)

Where:

  • app is an instance of express.
  • METHOD is an HTTP request method (lowercase).
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

There are two ways of using the router methods. Either we can define route (for example /users) and attach the methods to it, or we can create a new method for each route.

// Method 1
router.route('/users')
.get(function (req, res, next) { ... })
     .post(function (req, res, next) { ... });
    
// Method 2
router.get('/users', function (req, res) { ... });
router.post('/users', function (req, res) { ... });

Note: We can use the same (‘/users’) route for multiple methods like GET, POST within a Node application.

Route methods

A method which is derived from any one of the following HTTP methods, and it has to be attached to an instance of the express class. Here are the express routing methods corresponding to the HTTP methods of the same names. 

  • checkout
  • copy
  • delete
  • get
  • head
  • lock
  • merge
  • mkactivity
  • mkcol
  • move
  • m-search
  • notify
  • options
  • patch
  • post
  • purge
  • put
  • report
  • search
  • subscribe
  • trace
  • unlock
  • unsubscribe

app.all() is a special routing method used to load middleware functions at a path for all HTTP request methods. When this method is routed, the attached handler will be executed for requests to the specific route whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the HTTP module.

Route paths

The route paths in combination with a request method define the endpoints at which requests can be made. It can be strings, string patterns, or regular expressions.
The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths. If we need to use the dollar character ($) in a path string, enclose it escaped within ([ and ]). Additionally, Express uses path-to-regexp for matching the route paths. Query strings are not part of the route path. 
Examples of route paths based on strings:
This route path will match requests to the root route, /.

app.get('/', function (req, res) {
  res.send('root')
})

And this route path will match requests to /home.

app.get('/home', function (req, res) {
  res.send('home')
})

While this route path will match requests to /profile.text.

app.get('/profile.text', function (req, res) {
  res.send('profile.text')
})

 
Examples of route paths based on string patterns: 
This route path will match acd and abcd.

app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

And, this route path will match abcd, abbcd, abbbcd, and so on.

app.get('/ab+cd', function (req, res) {
  res.send('ab+cd')
})

While, this route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.

app.get('/ab*cd', function (req, res) {
  res.send('ab*cd')
})

Furthermore, this route path will match /abe and /abcde.

app.get('/ab(cd)?e', function (req, res) {
  res.send('ab(cd)?e')
})

 
Examples of route paths based on regular expressions:
This route path will match anything with an “a” in it.

app.get(/a/, function (req, res) {
  res.send('/a/')
})

And, this route path will match mybook and handbook, however not mybookshelf, bookshop, and so on.

app.get(/.*book$/, function (req, res) {
  res.send('/.*book$/')
})

Route parameters

These are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated through the req.params object, with the respective key name defined in the path of request method.

app.get(‘/users/:userId/orders/:orderId’, function (req, res) {
  res.send(req.params)
})

 
Here, for instance, let us imagine that we need order information for a particular user. So for this purpose, we have defined the above route with the route parameters (/:userId) and (/:orderId). This definition makes the ‘user Id’ and corresponding ‘order Id’ available through req.params.userId and req.params.orderId, without any complex coding.

Route handlers

It can be in the form of a function, an array of functions, or even combinations of both.
We can provide multiple callback functions that behave like middleware to handle a request. But, the only exception is that these callbacks might invoke next(‘route’) to bypass the remaining route callbacks.  Also, we can use this mechanism to impose pre-conditions on a route, and then pass control to subsequent routes if there’s no reason to proceed with the current route.

app.get('/getDetails', function (req, res, next) {
  console.log('invoke response using next callback function ...')
  next()
}, function (req, res) {
  res.send('Here are the details!....')
})

To conclude, we can generate a better responsive Node application with Express framework by using the above routing methodologies. Thus, routing in Node.js is no big deal! 
Read more tutorials on Node.js. From uploading images/Files to AWS S3 to a complete guide to debug Node.js app in a docker container.
Get guaranteed solutions from the best full-stack Node.js developers in the industry.

Looking for a Tech partner to dominate the digital world?

 

Annamalai

Tech lead at Agira, Around 10+ years of experience in IT industry; He demonstrated numerous success in various projects by directing the team with great guidance to apply the intense logics to accomplish the goal on time. Reliable working experience in modern web technologies, especially in Node.js and always loves to reserve his time in reading magazines & travelling.