Dirk Harriman Banner Image

 

Notes Node JS

Projects:

 

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.

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();

Route Definition

It takes the following structure:

app.METHOD(PATH, HANDLER)

Where:

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!