Route parameters in Express.js
Route parameters in Express.js are used to capture values from the URL and use them in your route handlers. They provide a way to pass dynamic data through the URL. This is useful for routes where the value varies, such as user IDs or product categories.
How Route Parameters Work
Route parameters are specified in the route path by placing a colon (:
) before the parameter name. When a request matches a route with a parameter, the value is extracted and can be accessed within the route handler.
Defining Route Parameters
To define route parameters, use a colon (:
) followed by the parameter name in the route path.
Example:
const express = require('express');
const app = express();
// Define a route with a route parameter
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Access the route parameter
res.send(`User ID is ${userId}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example:
:id
is a route parameter in the path/users/:id
.- If you navigate to
/users/123
, theuserId
variable in the route handler will be123
.
Accessing Route Parameters
Route parameters are accessed via the req.params
object. Each parameter name defined in the route path is a key in this object, with the corresponding value from the URL as its value.
Example:
app.get('/products/:category/:id', (req, res) => {
const category = req.params.category; // Access category parameter
const productId = req.params.id; // Access id parameter
res.send(`Product category: ${category}, Product ID: ${productId}`);
});
For a URL like /products/electronics/789
, req.params.category
will be electronics
, and req.params.id
will be 789
.
Optional Route Parameters
Express.js does not natively support optional parameters in routes. However, you can simulate optional parameters by defining multiple routes or using regular expressions in route definitions.
Example of Simulating Optional Parameters:
app.get('/search/:query?', (req, res) => {
const query = req.params.query || 'No query provided'; // Default if not provided
res.send(`Search query: ${query}`);
});
In this example, :query
is optional. If the URL is /search/
, query
will be undefined
, and the default value 'No query provided'
will be used.
Advanced Route Parameters with Regular Expressions
You can use regular expressions to define more complex routes with route parameters.
Example:
app.get('/files/*', (req, res) => {
const filePath = req.params[0]; // Everything after '/files/' is captured
res.send(`File path is ${filePath}`);
});
For a URL like /files/docs/2024/report.pdf
, req.params[0]
will be docs/2024/report.pdf
.
Summary
- Route Parameters: Defined in the route path with a colon (
:
) followed by the parameter name (e.g.,/users/:id
). - Accessing Parameters: Access route parameters using
req.params
(e.g.,req.params.id
). - Optional Parameters: Express doesn’t directly support optional parameters but can be simulated or handled with default values.
- Advanced Usage: Regular expressions can be used for more complex parameter capturing.
Route parameters are powerful for creating dynamic and flexible routes, allowing you to handle a variety of requests based on variable URL segments.