In web development, handling dynamic routes is a common requirement. For instance, you might want to display different content based on the user's ID or fetch data for a specific product. Express.js provides a powerful way to handle these scenarios using route parameters.
Route parameters allow you to capture parts of the URL as variables that you can use within your application logic. This makes it easy to create dynamic routes that respond to different inputs.
In Express.js, route parameters are defined by prefixing a colon (:) to a segment in the route path. For example, :userId is a route parameter that captures any value placed in that position of the URL.
When a request matches a route with parameters, the captured values are stored in an object called req.params. This object can be accessed within your route handler functions to retrieve the dynamic segments of the URL.
Let's explore some practical examples to understand how route parameters work in Express.js.
Suppose you have a simple application that displays user profiles. Each user has a unique ID, and you want to display their profile based on this ID.
const express = require('express');
const app = express();
const port = 3000;
// Define a route with a parameter
app.get('/user/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`User Profile for User ID: \${userId}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:\${port}/`);
});
In this example:
/user/:userId defines a parameter userId.http://localhost:3000/user/123, the output will be User Profile for User ID: 123.You can also define multiple parameters in a single route. For instance, consider an e-commerce application where you want to display product details based on both category and product ID.
const express = require('express');
const app = express();
const port = 3000;
// Define a route with multiple parameters
app.get('/products/:category/:productId', (req, res) => {
const category = req.params.category;
const productId = req.params.productId;
res.send(`Product Details for Category: \${category}, Product ID: \${productId}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:\${port}/`);
});
In this example:
/products/:category/:productId defines two parameters: category and productId.http://localhost:3000/products/electronics/102, the output will be Product Details for Category: electronics, Product ID: 102.Sometimes, you might want a parameter to be optional. Express.js does not natively support optional parameters directly in route definitions, but you can achieve this by using regular expressions.
const express = require('express');
const app = express();
const port = 3000;
// Define a route with an optional parameter
app.get('/user/:userId?', (req, res) => {
const userId = req.params.userId;
if (userId) {
res.send(`User Profile for User ID: \${userId}`);
} else {
res.send('No user ID provided');
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:\${port}/`);
});
In this example:
/user/:userId? makes the userId parameter optional.http://localhost:3000/user/456, the output will be User Profile for User ID: 456.http://localhost:3000/user, the output will be No user ID provided.Now that you have a good understanding of how to use route parameters in Express.js, you might want to explore more advanced routing techniques. In the next section, we will cover "Redirecting Requests in Express.js," which allows you to redirect users from one URL to another.
By mastering these concepts, you'll be well-equipped to build dynamic and responsive web applications using Express.js.