1. Introduction to Routing in Express.js
Routing refers to how an application’s endpoints (URIs) respond to client requests. In Express.js, routes define how HTTP requests (GET, POST, PUT, DELETE, etc.) should be handled.
Basic Route Syntax:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
2. Route Parameters
Route parameters allow capturing values from the URL and using them inside the route handler.
Example:
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
- :id is a route parameter, which can be accessed using req.params.id.
Multiple Route Parameters:
app.get('/user/:id/post/:postId', (req, res) => {
res.send(`User ID: ${req.params.id}, Post ID: ${req.params.postId}`);
});
3. Query Parameters
Query parameters are passed in the URL after ? and can be accessed using req.query.
Example:
app.get('/search', (req, res) => {
res.send(`Search Query: ${req.query.q}`);
});
Example request: http://localhost:3000/search?q=Node.js
4. Request Object (req)
The req object represents the HTTP request and contains:
- req.params → Route parameters
- req.query → Query parameters
- req.body → Data sent in the request body (requires express.json() middleware for JSON)
- req.headers → Request headers
5. Response Object (res)
The res object sends responses back to the client.
Common Response Methods:
res.send('Hello'); // Sends a simple response
res.json({ message: 'Success' }); // Sends a JSON response
res.status(404).send('Not Found'); // Sends a response with a status code
res.redirect('/home'); // Redirects to another route
6. Middleware for Handling Requests
To process JSON or form data, middleware is needed:
app.use(express.json()); // Parses JSON data
app.use(express.urlencoded({ extended: true })); // Parses form data
7. Handling POST Requests
To handle POST requests, use req.body:
app.post(‘/user’, (req, res) => {
res.json({ name: req.body.name, email: req.body.email });
});
Example Request (using Postman or Fetch API):
{
"name": "John",
"email": "john@example.com"
}
8. Handling 404 Errors
Define a catch-all route for undefined paths:
app.use((req, res) => {
res.status(404).send(‘Page Not Found’);
});