Express Routing is a powerful feature of the Express.js framework, a popular web application framework for Node.js. It provides a way to define how your application responds to client requests for specific endpoints, or routes. Routing allows you to map HTTP requests to the corresponding handler functions (controllers), where you define the logic for each request.
1. Basic Routing in Express
In Express, routes are defined by specifying a URL path and the HTTP method (such as GET, POST, PUT, DELETE) that the server should respond to.
Example of Basic Routing:
const express = require('express');
const app = express();
// Respond to GET request at root route
app.get('/', (req, res) => {
res.send('Hello World');
});
// Respond to GET request for a specific route
app.get('/about', (req, res) => {
res.send('This is the About page');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
- GET
/
responds with “Hello World” - GET
/about
responds with “This is the About page”
2. Route Parameters
Express allows you to define dynamic routes by using route parameters. These parameters are placeholders that match segments of the URL and can be accessed through req.params
.
Example:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});
- If you visit
/user/123
, the response will beUser ID is: 123
.
You can also define multiple parameters:
app.get('/user/:id/:name', (req, res) => {
const { id, name } = req.params;
res.send(`User ID: ${id}, User Name: ${name}`);
});
3. Query Parameters
Query parameters can be appended to the URL after a question mark (?
) and are accessed via req.query
.
Example:
app.get('/search', (req, res) => {
const { query, page } = req.query;
res.send(`Search term: ${query}, Page number: ${page}`);
});
- If the URL is
/search?query=express&page=2
, the response will beSearch term: express, Page number: 2
.
4. Route Methods
Express allows you to handle different types of HTTP requests (GET, POST, PUT, DELETE) at the same route or different routes.
Example:
// Handle GET request (retrieving data)
app.get('/item', (req, res) => {
res.send('GET request for item');
});
// Handle POST request (creating data)
app.post('/item', (req, res) => {
res.send('POST request for item');
});
// Handle PUT request (updating data)
app.put('/item/:id', (req, res) => {
res.send(`PUT request for item with ID: ${req.params.id}`);
});
// Handle DELETE request (deleting data)
app.delete('/item/:id', (req, res) => {
res.send(`DELETE request for item with ID: ${req.params.id}`);
});
5. Route Handlers (Callback Functions)
Express route handlers are just JavaScript functions that define the behavior when the route is matched. These handlers take two arguments: req
(request) and res
(response).
Example:
app.get('/hello', (req, res) => {
res.send('Hello, World!');
});
You can also chain multiple handlers for a single route, which is useful for middleware or pre-processing.
Example with Middleware:
app.use('/user/:id', (req, res, next) => {
console.log(`Request to /user with ID: ${req.params.id}`);
next(); // Continue to the next middleware or route handler
});
app.get('/user/:id', (req, res) => {
res.send(`User details for ID: ${req.params.id}`);
});
6. Route Groups with Express Router
The Router
object in Express helps organize routes into modular, reusable units. This is especially useful in large applications where routing logic can get complex.
Example using express.Router
:
const express = require('express');
const app = express();
const router = express.Router();
// Define routes for 'users'
router.get('/', (req, res) => {
res.send('List of all users');
});
router.get('/:id', (req, res) => {
res.send(`User details for ID: ${req.params.id}`);
});
// Mount the router to a specific path
app.use('/users', router);
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example:
/users/
will display “List of all users”./users/:id
will display “User details for ID: {id}”.
This helps keep routes organized and avoid having one massive list of route definitions.
7. Route Chaining
You can chain multiple route handlers for the same route and HTTP method. This allows you to reuse code and organize logic more efficiently.
Example:
app.route('/book')
.get((req, res) => {
res.send('Get all books');
})
.post((req, res) => {
res.send('Add a new book');
})
.put((req, res) => {
res.send('Update a book');
});
This eliminates repetitive code for the same path and HTTP method.
8. Handling Errors in Routes
You can handle errors by using next
in route handlers. If an error occurs, pass it to the next middleware (typically an error handler).
Example:
app.get('/data', (req, res, next) => {
try {
// Imagine some logic that can throw an error
throw new Error('Something went wrong!');
} catch (error) {
next(error); // Pass the error to the next middleware (error handler)
}
});
// Global error handler
app.use((err, req, res, next) => {
res.status(500).send(`Error occurred: ${err.message}`);
});
9. Using HTTP Status Codes in Responses
Express allows you to set custom HTTP status codes in your responses using res.status()
. This helps communicate the outcome of the request (success, error, etc.).
Example:
app.get('/success', (req, res) => {
res.status(200).send('Request was successful');
});
app.get('/notfound', (req, res) => {
res.status(404).send('Resource not found');
});
app.get('/servererror', (req, res) => {
res.status(500).send('Internal server error');
});
10. Route Handling with Wildcards
You can use wildcard routes to handle dynamic paths or catch-all routes.
Example:
app.get('*', (req, res) => {
res.send('Catch-all route');
});
This route will match any request that hasn’t been matched by other routes.
Conclusion
Express routing is one of the fundamental aspects of building web applications with Express.js. It provides a simple yet powerful way to map URLs to specific functionality and handle client requests based on the HTTP method. By organizing your routes and using features like route parameters, query parameters, routers, and middleware, you can easily manage complex web applications.
For large applications, it’s common to modularize routes with express.Router()
, allowing for a scalable and maintainable route structure.