Latest Code Tutorials

Express Router: How to Use Routing in Node.js

Express apps utilize routers that are essentially containers for a set of middleware. We can put this middleware holder only on a specific route, which allows us to keep our logic in separate files and bring them together on our terms.

Express Router

Express Router is a built-in class that refers to how an application’s endpoints (URIs) respond to client requests. In addition, the express router class helps create route handlers.

You define routing using the Express app object methods that correspond to HTTP methods; for example, app.get() to handle GET requests and to handle POST requests. For a full list, see the app.METHOD.

You can also use the app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function (See Using middleware for details).

These routing methods specify the callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method.

In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.

The routing methods can have more than one callback function as arguments.

With multiple callback functions, it is important to provide next as an argument to the callback function and then call next() within the function’s body to hand off control to the next callback.

See the basic routing.

// server.js

const express = require('express')
const app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')

Now, let’s head back to our demo project.

Step 1: Create an express project.

Create one project folder and go inside that folder.

mkdir erouter && cd erouter

Now, initialize the package.json file using the following command.

npm init -y

Express Router Tutorial Example From Scratch

Now, install the express using the following command.

npm install express --save

# or

yarn add express

Step 2: Let us write the first express route.

Now, inside the root folder. Create one file called server.js and add the following code.

// server.js

const express = require("express");
const app = express();
const PORT = process.env.PORT = 3000;

let router = express.Router();

  res.json({'message' : 'Ping Successfull'});


  console.log('Server is running at PORT:',PORT);

First, we have imported all the required modules, created an object of a router, and then defined the root route. Then we have used the middleware saying that if any request comes with the ‘/api’, it will call the router function with its route. So in our case, we will get a JSON response.

So this was the example of basic routing that we used to do when creating a web application with express on the Node.js platform.

Express router methods

Express supports the main following routing methods.

  1. GET
  2. POST
  3. PUT
  4. HEAD

There are still other methods, but mainly we used the above methods in a web application. In addition, there is a routing method called app.all(), which is not derived from any HTTP method.

The routing method gets loaded for functions at a specified path for all request methods.

The route path is used to define an endpoint where requests can be made. It is like a backend endpoint. In the Express, route paths can be string patterns or regular expressions.

In the above example, the route path is below.

// server.js

  res.json({'message' : 'Ping Successfull'});

Here, the router path is “/.”

The route parameters capture the values specified to a particular position in the URL. Thus, they are called URL segments.

The values obtained are made available in a req.params object, using the name of the route parameter specified in the path as the keys of the values.

Route parameter is significant in functionality like edit, update, and delete. Therefore, we generally pass the ID on the parameter and extract it from the request. The syntax is like this.


At Express Router, we can access the ID using the following code.


In the req.params, the following will be available: { “id”: “1” }

So, we can access the 1 using the following code.

Express Router POST Request

The basic syntax of the express post route is the following.

// server.js'/', function(req, res){
   res.send('It's a post route, grab the data and save in the Mongo');

Inside the router post method, we save the data from the req and extract that data from the req and save the data inside the database.

Just like the following code.

router.route('/store').post(function (req, res) {
  let model = new Model(req.body);
    .then(game => {
    res.status(200).json({'model': 'Your data is saved'});
    .catch(err => {
    res.status(400).send("unable to save to database");

So, here we have used the Mongoose model to save the data in the MongoDB database. It is just a real-time example that will show you how to create your post request and save the data in the database.

Router-level middleware

Router-level middleware works the same way as application-level middleware, except it is bound to an instance of express.Router().

// server.js

const app = express();
const router = express.Router();

router.use(function (req, res, next) {

router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl);
}, function (req, res, next) {
  console.log('Request Type:', req.method);

That’s it for this tutorial.

See also

Node express image upload

How to use a template engine in express

How to serve a static file in express

Express error handling

Express post request

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.