Lesson 33 of 50 – Routing in Express.js
66% Completed
66%

Routing in Express.js

Routing determines how an Express.js application responds when a client requests a particular URL using an HTTP method such as GET, POST, PUT, or DELETE.

In this lesson: Learn basic routes, HTTP methods, route parameters, query parameters, route handlers, and Express Router.

1. What Is Routing?

Routing is the process of defining what happens when a user visits a specific URL on a website or API.

For example, a website may contain these routes:

URL Purpose
/ Home page
/about About page
/contact Contact page
/students Student information

Express checks the incoming request and runs the matching route handler.

2. Basic Route Syntax

The general syntax of an Express GET route is:

app.get('URL', (req, res) => {
    // Handle the request
});
  • app.get() defines a route for GET requests.
  • req contains information about the request.
  • res is used to send the response.
Example: Home Route
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Soopro Pathshala');
});

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

Run node app.js and open http://localhost:3000.

Output: Welcome to Soopro Pathshala

3. Create Multiple Routes

You can create multiple routes in the same Express application. Each route can return a different response.

Example: Home, About, and Contact
const express = require('express');
const app = express();

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

app.get('/about', (req, res) => {
    res.send('About Page');
});

app.get('/contact', (req, res) => {
    res.send('Contact Page');
});

app.listen(3000, () => {
    console.log('Server started');
});

Test these URLs:

  • http://localhost:3000/
  • http://localhost:3000/about
  • http://localhost:3000/contact

4. HTTP Methods in Routing

HTTP methods tell the server what kind of operation the client wants to perform.

Method Common Purpose Express Syntax
GET Retrieve information app.get()
POST Create or submit information app.post()
PUT Replace a resource app.put()
PATCH Partially update a resource app.patch()
DELETE Delete a resource app.delete()
Example: Different HTTP Methods
const express = require('express');
const app = express();

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

app.post('/students', (req, res) => {
    res.send('Create a student');
});

app.put('/students/1', (req, res) => {
    res.send('Replace student 1');
});

app.patch('/students/1', (req, res) => {
    res.send('Update part of student 1');
});

app.delete('/students/1', (req, res) => {
    res.send('Delete student 1');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
Note: Typing a URL into a browser address bar normally sends a GET request. Use an API client such as Postman to test POST, PUT, PATCH, and DELETE requests.

5. Route Parameters

Route parameters allow you to capture values directly from a URL. They are useful when accessing a particular student, product, or other resource.

Example URL:

http://localhost:3000/students/101

In the route /students/:id, the colon indicates that id is a route parameter.

Example: Read a Route Parameter
const express = require('express');
const app = express();

app.get('/students/:id', (req, res) => {
    const studentId = req.params.id;

    res.send('Student ID: ' + studentId);
});

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

Visit:

http://localhost:3000/students/101
Output: Student ID: 101

Multiple Route Parameters

app.get('/students/:id/courses/:courseId', (req, res) => {
    res.json({
        studentId: req.params.id,
        courseId: req.params.courseId
    });
});

For a URL such as /students/101/courses/5, the response contains student ID 101 and course ID 5.

6. Query Parameters

Query parameters are values added after a question mark (?) in a URL. They are commonly used for searching, filtering, sorting, and pagination.

Example URL:

http://localhost:3000/search?name=Amit&course=Node.js
Example: Read Query Parameters
const express = require('express');
const app = express();

app.get('/search', (req, res) => {
    const name = req.query.name;
    const course = req.query.course;

    res.json({
        studentName: name,
        studentCourse: course
    });
});

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

Expected response:

{
  "studentName": "Amit",
  "studentCourse": "Node.js"
}
Remember: req.params reads route parameters, while req.query reads query-string parameters.

7. Route Parameters vs Query Parameters

Feature Route Parameters Query Parameters
Example URL /students/101 /students?id=101
Access using req.params req.query
Common use Identify a specific resource Filter or search resources
URL position Part of the route path After the question mark

8. Route Handlers

A route handler is a function that runs when an incoming request matches a route. You can provide multiple callback functions for a route and pass control using next().

Example: Multiple Route Handlers
const express = require('express');
const app = express();

function firstHandler(req, res, next) {
    console.log('First handler executed');
    next();
}

function secondHandler(req, res) {
    res.send('Second handler sent the response');
}

app.get('/example', firstHandler, secondHandler);

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

When you visit /example, the first handler runs and calls next(). The second handler sends the response.

9. Organize Routes Using Express Router

In a larger application, keeping every route in one file can make the code difficult to maintain. Express Router allows you to organize routes into separate files.

Step 1: Create a Folder Structure

express-routing/
│
├── app.js
├── package.json
└── routes/
    └── studentRoutes.js

Step 2: Create routes/studentRoutes.js

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

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

router.get('/:id', (req, res) => {
    res.send('Student ID: ' + req.params.id);
});

module.exports = router;

Step 3: Use the Router in app.js

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

const studentRoutes = require('./routes/studentRoutes');

app.use('/students', studentRoutes);

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

Test the routes:

  • http://localhost:3000/students — All Students
  • http://localhost:3000/students/101 — Student ID: 101
Benefit: Express Router keeps related routes together and makes applications easier to organize and maintain.

10. Handle Unknown Routes

If no route matches an incoming request, you can provide a custom 404 response.

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

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

app.use((req, res) => {
    res.status(404).send('404 - Route Not Found');
});

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

The fallback middleware should appear after the routes you want to match first.

11. Common Routing Mistakes

Problem Solution
Cannot GET /about Check that the GET route exists and the URL is correct.
Using req.query for a route ID Use req.params for path parameters.
Response is never sent Ensure the handler sends a response or passes control appropriately.
404 middleware runs too early Move the fallback middleware after the intended routes.
Testing POST by entering a URL in the browser Use Postman or another HTTP client to send a POST request.

12. Practical Assignment

Assignment: Student Routing System

Create an Express application with these requirements:

  1. Create a home route /.
  2. Create an about route /about.
  3. Create a GET route /students that returns a student list as JSON.
  4. Create a route /students/:id that displays a student ID.
  5. Create a route /search?course=Node.js that reads the course query parameter.
  6. Create a POST route /students that sends a confirmation response.
  7. Move student routes into a separate file using Express Router.
  8. Return a custom 404 response for unknown URLs.
Lesson Summary: You learned how Express routing works, how to create routes for different HTTP methods, how to read route and query parameters, how to use multiple route handlers, and how to organize routes with Express Router.

Test Your Knowledge – MCQ Quiz

Select the correct answer for each question.

1. Which Express property accesses route parameters?
2. Which method is commonly used to retrieve data?
3. What is the purpose of express.Router()?