agyanadda@gmail.com

Express.js Routing

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 16 of 30

Methods

app.get, app.post, app.put, app.patch, app.delete, and app.all for every method.

Route parameters

/users/:id matches /users/42 and gives req.params.id === '42' (always a string; convert with Number()).

Query strings

/search?q=node&page=2 → req.query.q, req.query.page.

Request body

With express.json(), POSTed JSON is in req.body.

express.Router

Split routes into files. Create a router in routes/users.js, add routes to it, export it, then mount it: app.use('/api/users', usersRouter). Inside the router, / means /api/users.

Chaining

router.route('/:id').get(show).put(update).delete(remove) groups methods for one path.

Order matters

Express checks routes top to bottom and uses the first match. Put specific paths (/users/me) before parameter paths (/users/:id), and the 404 handler last.

Example

Example — Users router JavaScript
// routes/users.js
import { Router } from 'express';
const router = Router();

const users = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi' }];

router.get('/', (req, res) => {
  const q = (req.query.q ?? '').toLowerCase();
  res.json(users.filter((u) => u.name.toLowerCase().includes(q)));
});

router.get('/:id', (req, res) => {
  const user = users.find((u) => u.id === Number(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

router.post('/', (req, res) => {
  const user = { id: users.length + 1, name: req.body.name };
  users.push(user);
  res.status(201).json(user);
});

export default router;

// app.js
// import usersRouter from './routes/users.js';
// app.use('/api/users', usersRouter);

GET /api/users?q=as returns [{"id":1,"name":"Asha"}], GET /api/users/2 returns Ravi, /api/users/9 returns 404, and POST /api/users with {"name":"Neha"} returns 201 with the new user.

Test Yourself With Exercises

Exercise 1 Multiple Choice

In /users/:id, how do you read the id?

Exercise 2 True / False

Values in req.params are strings.

Exercise 3 Fill in the Blank

Group routes in their own file with express.___()

Frequently Asked Questions

Because /users/:id is defined first and matches 'me' as the id. Move the /users/me route above /users/:id.