How to implement Express Routing

Routing is used extensively on both client and server-side. Express routing is server-side routing and is responsible for responding to different URLs with different HTTP methods (GET, POST, PUT, DELETE) requested asked by clients.

Routing is an important feature of Express, and it provides a simple interface for handling an incoming URL request from a client by a certain piece of code at the server. Based on user requests, server code responses can be reading data from a database, or writing data to a database, or serving a static HTML page based on client requests.

In an Express, we can handle and respond to the particular URI (Uniform Resources Identifier) through the HTTP Client request method (GET, POST, DELETE, PUT, and so on). It should handle the following.

  1. Determine who should handle particular URL with different HTTP method at server.
  2. Retrieve params query if any on URL at server side.
  3. Serve the client content request if it asking for.

In this tutorial, we’ll learn how to configure Express routes in detail. How we can handle different HTTP method requests and how to retrieve data from route params.

How to implmement Express routing and its syntax

Express Routes determine what and who should responsible for handling when a particular incoming URL request is made by a client. The syntax of express routes handler.

const router = express.Router();

app.method(path, handler);

// Request to root path or domain
app.get('/', (req, res) => {  }

In the express have router class, we can use the router class method on the HTTP verbs – GET, PUT, DELETE and etc. The syntax of Express routes where.

  • Path: The path is the route at which the request will run
  • Handler: Each route can have one or more handler functions, which are executed when the route is matched. In handler have three parameters. The req for request, res for respond and next is optinal.

Example :router.get(‘/’, (req, res, next) => {   res.send(‘Hello world’);});


Express routes example

Let demonstrate a few examples of Express routing and we are using an express route to access the resources of HTTP get / or root, /about, /contact, etc. Let first create an express project by running the following.

npm init 
// to create express project

First, create an app.js file in the root folder, we will demonstrate an express router example.

Express router example basic GET request at root

Let demonstrate an express routing example of the HTTP GET method, at Express server-side let’s add the following code.

const express = require('express');

const app = express();

const port = 3000;

//HTTP GET request for root
app.get('/', (req, res) => {
    res.send('Hello world from server ');
});

app.listen(port, () => {
    console.log('Server startd on port ' +port);
 });

We need to import express, assign it to app const and we have added get on the app to respond to GET request of path root. Here is a screenshot of what we get.

Express routing example

Express route method

A route method of Express is derived from one of the HTTP methods and is attached to an instance of the express class or express.Router() method.

const express = require('express');
const app = express();
OR
const router = express.router();

We can have the following route methods we can attach to the route class.

Route methodDescription
router.get(‘path’, callback(req, res, next))HTTP GET request for URL of PATH, we have requested, respond, and next can be optional middleware.
router.get(‘path:/id’, callback(req, res, next))HTTP GET request for URL of PATH with id of particular data.
router.pos(‘path’, callbackFunction)HTTP POST request of having the same parameter of get request, where req object has data to POST to the database.
router.put(‘path/:id’, callbackFunction)HTTP PUT method to modify data of having id at database.
router.delete(‘path/:id’, callbackFunction)An HTTP DELETE request to delete data of id at a database.
router.get('api/book/:id', (req, res) => {
 const id = req.params.id;
 // code to retrieve data of having id
});


router.delete('api/book/:id', (req, res, next) => {
 const id = req.params.id;
 // code to delete data of having id
}

app.get('/about', (req,res) => {
   res.send('About Us: ...');
})
const express = require('express');
const path = require('path');

const port = 3000;

const app = express();
const index = require('./routes/index');
const articles = require('./routes/articles');
const categories = require('./routes/categories');
const manage = require('./routes/manage');
const manage = require('./routes/blog');

//set static folder

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/articles', articles);
app.use('/categories', categories);
app.use('/manage', manage);

app.listen(port, () =>{
    console.log('Server startd on port ' +port);
})

Step 2: Define routing for index, /about and /contact page

In the root folder create a folder called routes, create the following files index.js, about.js and contact.js file. Add the following code in the index.js file

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

router.get('/', (req, res, next) => {
    res.send('INDEX');
});

module.exports = router;

Add route code for about.js file

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

router.get('/', (req, res, next) => {
    res.send('ABOUT');
});

module.exports = router;

Add route code for contact.js file

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

router.get('/', (req, res, next) => {
    res.send('CONTACT');
});

module.exports = router;

NOTE: We can access root file as http://localhost:3000, we can access about page at http://localhost:3000/about

Example 2 : We are accessing the sub path, eg we are accessing the http://localhost:3000/blog/articles/add.

Step 1: In the routes, folder adds a new file called blog.js file to access the routing code for blog and blog/articles/add.

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

router.get('/', (req, res, next) => {
    res.send('BLOG');
});

router.get('/articles/add', (req, res, next) => {
    res.render('add_article', {title: 'Create Article'});
});

module.exports = router;

Step 2: Create a folder view in the root folder and add two new files for the template, add_article.pug and layout.pug. Add the following code in layout.pug file

doctype html
html
  head
    title BooksBlog
  body
    block content

add the following code in add_article.pug file

extends layout

block content
  h1 #{title}

Example 3: Accessing the particular sub-path like particular articles like http://localhost:3000/manage/books/edit/2

Step 1:  We will first add manage.js code of route in routes folder.  We can access to http://localhost:3000/manage/books/edit/2, http://localhost:3000/manage/books, http://localhost:3000/manage/books/add

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

router.get('/books', (req, res, next) => {
  res.render('manage_books', {title: 'Manage books'});
});

router.get('/books/add', (req, res, next) => {
  res.render('add_book', {title: 'Create book'});
});

router.get('/books/edit/:id', (req, res, next) => {
  res.render('edit_book', {title: 'Edit book'});
});

module.exports = router;

Step 2: In view folder, we will have to add 3 file books.pug, edit_book.pug and edit_book.pug. We will add code for books.pug and same code can be added to other two files.

extends layout

block content
  h1 #{title}
Spread the love

Leave a Comment

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

Scroll to Top