JavaScript

Routing in Express.js

Hello in this tutorial, we will understand how to handle routing in a Node.js application running on an Express.js server.

1. Introduction

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Express.js routing - verifying node
Fig. 1: Verifying node and npm installation

To understand routing in the Node.js application we will use the following method.

app.method(path, handler)

where –

  • method is applied differently to any one of the HTTP verbs like HTTP GET, HTTP POST, HTTP PUT, HTTP PATCH, and HTTP DELETE
  • path denotes the route at which the request will run

2. Routing in Express.js

To set up the Express.js server, we will need to navigate a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the Express.js dependency.

package.json

{
  "name": "express-routing-tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2 Creating an API file

Create an API file in the src/routes folder that will be used to specify the handler mapping for the request methods. The methods will include a callback that accesses the request and response arguments.

HTTP methodApplication endpointHandler method
GET/health
GET/usersindex
GET/users/profilesprofiles
GET/users/profiles/:idprofile

Add the following code to the API file and you are free to change these details as per your application. Similarly, you can create other handler methods to support other HTTP methods.

users.js

const index = (request, response) =< {
    response.status(200).json({ info: 'Hello user!' });
};

const profiles = (request, response) =< {
    response.status(200).json({ info: 'Welcome to profiles page!' });
};

const profile = (request, response) =< {
    const id = parseInt(request.params.id)
    response.status(200).json({ info: `Welcome to profile : ${id}` });
};

module.exports = {
    index,
    profiles,
    profile
};

2.3 Creating an index file

Create an index file that will act as an entry point for our server. The file will require the express module and exported functions from users.js file. This file will set the HTTP request method for each endpoint and map it to a relevant function.

idex.js

// base setup
const express = require('express');
const users = require("./src/routes/users");
const app = express();
const port = 10091;

app.use(express.json());

// health check route
app.get('/', (request, response) =< {               // url - http://localhost:10091/
    const now = new Date();
    response.status(200).json({ info: `Health check successfully ran at : ${now}` });
});

// application routes
// users
app.get('/users', users.index);                     // url - http://localhost:10091/users
app.get('/users/profiles', users.profiles);         // url - http://localhost:10091/users/profiles
app.get('/users/profiles/:id', users.profile);      // url - http://localhost:10091/users/profiles/1

// starting the server
app.listen(port, () =< {
    console.log(`Application listening on port ${port}`)
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown in Fig. 4. If everything goes well the application will be started successfully on port number 10091.

Express.js routing - starting the app
Fig. 2: Starting the application

4. Project Demo

When the application is started, open the Postman tool to hit the application endpoints. You are free to choose any tool of your choice.

Application endpoints

Similarly, you can create other endpoints. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned:

  • Steps to setup Node.js
  • Sample programming stuff to routing via Express.js

You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a programming tutorial on routing in Express.js

Download
You can download the full source code of this example here: Routing in Express.js

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button