Express.js & REST APIs
Node.js Express Routing
Routing maps an HTTP method and path to a handler. Express supports route parameters, query strings, chained handlers and Router instances for splitting a large API into files.
What is Express Routing in Node.js?
Routing maps an HTTP method and path to a handler. Express supports route parameters, query strings, chained handlers and Router instances for splitting a large API into files.
Express Routing example
JavaScript
// routes/jobs.js
import { Router } from 'express';
const router = Router();
router.get('/', listJobs); // GET /api/jobs
router.get('/:id', getJob); // GET /api/jobs/123
router.post('/', requireAuth, createJob);
router.put('/:id', requireAuth, updateJob);
router.delete('/:id', requireAuth, deleteJob);
export default router;
// index.js
app.use('/api/jobs', jobsRouter);Reading params, query and body
JavaScript
router.get('/:id', (req, res) => {
req.params.id; // '123' — from the path
req.query.page; // '2' — from ?page=2
req.body; // parsed JSON on POST/PUT
res.json({ id: req.params.id });
});Key points to remember
- Routes are matched in the order they are registered — put specific paths before parameterised ones.
- A Router keeps each resource in its own file.
- Every param and query value is a string.
Common mistakes with Express Routing
- Declaring /jobs/:id before /jobs/featured, so "featured" is treated as an id.
- Sending two responses in one handler, which throws ERR_HTTP_HEADERS_SENT.
Node.js Express Routing— Interview Questions & FAQs
What is the difference between req.params and req.query?+
req.params holds values from the path pattern, such as :id in /jobs/:id. req.query holds the parsed query string after the question mark.
