Routing in Express.js refers to defining endpoints (URLs) of your application and determining how the server responds to client requests.
Routes are essential for building REST APIs or web applications.
Explanation:
app.get(path, callback) – Handles GET requests to a specific path.
res.send() – Sends a response to the client.
Express supports all HTTP methods:
| Method | Usage Example |
|---|---|
| GET | app.get('/users', ...) |
| POST | app.post('/users', ...) |
| PUT | app.put('/users/:id', ...) |
| DELETE | app.delete('/users/:id', ...) |
| PATCH | app.patch('/users/:id', ...) |
Example: CRUD operations for users
Route parameters allow you to capture values in the URL.
URL: /users/123 → Response: User ID is 123
Query parameters are passed after ? in the URL.
URL: /search?q=express → Response: You searched for: express
You can chain multiple handlers for a single route:
Express allows you to create modular route handlers using express.Router().
/user/profile → User Profile
/user/settings → User Settings
Use Router for modular code.
Use consistent route naming (plural nouns for resources: /users, /posts).
Separate routes into different files for large projects.
Routing is the backbone of any Express.js application, and mastering it is crucial for building RESTful APIs and full-stack apps.
Take quizzes related to this topic and see where you stand!
Start Quiz Now