Express.js Routing

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It facilitates the rapid development of Node-based web applications. Express simplifies routing, handling HTTP requests, rendering HTML views, and managing middleware.

What is Routing?

Routing in Express.js refers to how an application’s endpoints (URIs) respond to client requests. It determines how an application responds to a client request for a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).

Setting Up Express.js

Installation

First, ensure Node.js and npm (Node Package Manager) are installed on your system. Then, create a new project directory and initialize a Node.js project:

				
					mkdir express-routing-example
cd express-routing-example
npm init -y

				
			

Basic Setup

Install Express.js using npm:

				
					npm install express

				
			

Create an app.js file and set up a basic Express server:

				
					const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

				
			

Run the server:

				
					node app.js

				
			

Navigate to http://localhost:3000 in your browser. You should see “Hello, World!”.

Basic Routing

Express.js provides methods to define routes for various HTTP methods. The most common methods are:

  • app.get(): Defines a route for the GET method.
  • app.post(): Defines a route for the POST method.
  • app.put(): Defines a route for the PUT method.
  • app.delete(): Defines a route for the DELETE method.

Example: Basic Routes

Let’s define routes for GET and POST methods:

				
					app.get('/hello', (req, res) => {
  res.send('Hello from GET route!');
});

app.post('/hello', (req, res) => {
  res.send('Hello from POST route!');
});

				
			

Output:

  • Navigating to http://localhost:3000/hello will display “Hello from GET route!”.
  • Sending a POST request to http://localhost:3000/hello (e.g., using Postman) will display “Hello from POST route!”.

Route Parameters

Route parameters are named URL segments that capture values at specific positions in the URL.

Example: Route Parameters

				
					app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`User ID: ${userId}`);
});

				
			

Output:

Navigating to http://localhost:3000/users/123 will display “User ID: 123”.

Query Parameters

Query parameters are URL segments that capture values at specific positions in the URL after the ?.

Example: Query Parameters

				
					app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search query: ${query}`);
});

				
			

Output:

Navigating to http://localhost:3000/search?q=express will display “Search query: express”.

Handling Different HTTP Methods

Express allows you to handle different HTTP methods for the same route.

Example: Handling Different HTTP Methods

				
					app.route('/book')
  .get((req, res) => {
    res.send('Get a book');
  })
  .post((req, res) => {
    res.send('Add a book');
  })
  .put((req, res) => {
    res.send('Update the book');
  });

				
			

Output:

  • GET /book will display “Get a book”.
  • POST /book will display “Add a book”.
  • PUT /book will display “Update the book”.

Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can execute code, modify the request and response objects, end the request-response cycle, and call the next middleware function.

Example: Middleware

				
					app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

app.get('/', (req, res) => {
  res.send('Middleware example');
});

				
			

Output:

Each request to the root URL will log the current timestamp to the console.

Advanced Routing

Nested Routes

You can create nested routes using Express Router.

				
					const router = express.Router();

router.get('/info', (req, res) => {
  res.send('User Info');
});

app.use('/users', router);

				
			

Output:

Navigating to http://localhost:3000/users/info will display “User Info”.

Route Groups

Route groups allow you to apply middleware to a group of routes.

				
					const router = express.Router();

router.use((req, res, next) => {
  console.log('User Middleware');
  next();
});

router.get('/profile', (req, res) => {
  res.send('User Profile');
});

app.use('/users', router);

				
			

Output:

Each request to /users/profile will log “User Middleware” to the console.

Error Handling

Express has built-in error-handling middleware functions.

				
					app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

				
			

Output:

If an error occurs, “Something broke!” will be sent as the response.

Express.js routing is a powerful feature that allows developers to define how an application responds to client requests at different endpoints. With the ability to handle various HTTP methods, utilize route and query parameters, and implement middleware, Express.js offers a robust and flexible solution for building web applications. Understanding these concepts is crucial for developing efficient and scalable Node.js applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India