Concept Explanation
If Node.js is the engine, Express is the steering wheel and the dashboard. Routing defines how your application responds to client requests to particular endpoints (URIs).
In a professional app, you don't put all your routes in one file. You use the express.Router to create modular, mountable route handlers.
Syntax or Core Structure
Modular Routing
// routes/userRoutes.js
import express from 'express';
const router = express.Router();
router.get('/:id', (req, res) => {
const userId = req.params.id;
res.json({ id: userId, name: "Alice" });
});
export default router;
// app.js
app.use('/users', userRoutes);
Best Practices
- RESTful Naming: Use nouns, not verbs.
GET /booksis better thanGET /get-all-books. - Version your API: Start your routes with
/api/v1/. This allows you to make big changes later without breaking old apps. - Status Codes: Always send the correct HTTP status code.
201for Created,400for Bad Request,404for Not Found.
Practice Exercises
- The Parameter Grabber: Create a route that accepts a
categoryand apriceas URL parameters and returns them in a JSON object. - The Status Tester: Write a route that returns a
418 I'm a teapotstatus code just for fun. - The API Architect: Plan out the 5 main REST routes for a "To-Do List" application (Create, Read All, Read One, Update, Delete).