googleads
Routing in Node.js tutorial with specific examples | Express routing| Node.js
preloder
Node.js Quick Tips Web Development

Understanding routing in Node.js

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 :

.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:

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.

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, /.

And this route path will match requests to /home.

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

 

Examples of route paths based on string patterns: 

This route path will match acd and abcd.

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

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

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

 

Examples of route paths based on regular expressions:

This route path will match anything with an “a” in it.

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

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.

 

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.

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.

Like What You're Reading ?

 

The following two tabs change content below.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

[contact-form-7 id="120788" title="Web Page Form"]

Schedule Your Call