Express provides a robust set of features to develop web and mobile applications. Routing is one of the core concepts that enables you to manage HTTP requests and map them to specific functions.
Node.js Express Routing
1. Basic Routing
Routing refers to how an application’s endpoints (URIs) respond to client requests. Express allows you to define routes for HTTP methods like GET, POST, PUT, DELETE, etc. Here's how you can set up a basic route:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express Routing!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
In this example, when you visit the root URL ("/"), the server will respond with "Welcome to Express Routing!"
2. Route Parameters
Express allows you to capture route parameters, making your routes dynamic. For example:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
This route captures the user ID from the URL and returns it as a response. For example, visiting /user/5
will return "User ID is 5".
3. HTTP Methods
Express allows you to handle different HTTP methods. You can define routes for GET, POST, PUT, DELETE, etc. Here's an example for a POST route:
app.post('/submit', (req, res) => {
res.send('POST request received');
});
This route listens for POST requests at the "/submit" endpoint and sends a response back when the route is accessed.
4. Route Handling with Multiple Methods
You can also handle multiple methods for the same route. For example:
app.route('/user/:id')
.get((req, res) => {
res.send('GET user by ID');
})
.put((req, res) => {
res.send('PUT user by ID');
})
.delete((req, res) => {
res.send('DELETE user by ID');
});
This example defines three HTTP methods (GET, PUT, DELETE) for the same route. Each method has its own handling function.
5. Conclusion
Routing is one of the essential features in Express that helps you manage different HTTP requests. With route parameters, HTTP methods, and multiple method handling, you can build dynamic web applications with ease.