Express JS Request params
In Express.js, request parameters (or params) are used to capture dynamic values in the URL. They are commonly used in routes where the server needs to handle requests that include dynamic segments, such as user IDs, product names, or other variables in the URL.
Express provides a simple way to extract these dynamic values from the URL and make them accessible in the route handler via the req.params
object.
Types of Request Parameters in Express.js
- Route Parameters: Dynamic segments defined in the URL pattern of a route.
- Query Parameters: Key-value pairs appended to the URL after a question mark (
?
). - Body Parameters: Data sent in the body of a POST, PUT, or PATCH request (handled separately).
1. Route Parameters
Route parameters are part of the URL defined with a colon (:
) in the route path. They allow you to capture dynamic values from the URL.
Example:
const express = require('express');
const app = express();
// Define a route with a route parameter `:userId`
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId; // Access the dynamic `userId` from the URL
res.send(`User ID is ${userId}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
If you make a request to http://localhost:3000/users/123
, the response will be:
User ID is 123
req.params.userId
captures the value123
from the URL/users/123
.
Multiple Route Parameters
You can define multiple route parameters by adding more dynamic segments to the URL.
app.get('/users/:userId/posts/:postId', (req, res) => {
const { userId, postId } = req.params; // Destructure the params object
res.send(`User ID: ${userId}, Post ID: ${postId}`);
});
For the URL http://localhost:3000/users/1/posts/42
, the response will be:
User ID: 1, Post ID: 42
2. Query Parameters
Query parameters are key-value pairs appended to the URL after a ?
. They provide additional information or filters for the request. Query parameters are not part of the route path itself, but they are part of the URL.
Example:
app.get('/search', (req, res) => {
const { term, category } = req.query; // Access query parameters
res.send(`Search term: ${term}, Category: ${category}`);
});
For the URL http://localhost:3000/search?term=books&category=fiction
, the response will be:
Search term: books, Category: fiction
req.query.term
captures the valuebooks
from the query string?term=books
.req.query.category
captures the valuefiction
from the query string&category=fiction
.
3. Optional Route Parameters
Route parameters can be made optional by adding a ?
after the parameter name.
app.get('/users/:userId/posts/:postId?', (req, res) => {
const { userId, postId } = req.params;
if (postId) {
res.send(`User ID: ${userId}, Post ID: ${postId}`);
} else {
res.send(`User ID: ${userId}, no post ID provided`);
}
});
- If you visit
/users/1/posts/42
, the response isUser ID: 1, Post ID: 42
. - If you visit
/users/1/posts/
, the response isUser ID: 1, no post ID provided
.
4. Regular Expressions in Route Parameters
You can also use regular expressions to constrain the values for route parameters.
Example:
// Route only matches if userId is a number
app.get('/users/:userId(\\d+)', (req, res) => {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);
});
- This route will match URLs like
/users/123
but not/users/abc
, because\d+
is a regular expression that only matches one or more digits.
5. Handling Route Parameters in Middleware
Middleware functions can also access and manipulate route parameters. This can be useful for tasks like validating or transforming parameters before reaching the main route handler.
Example of Parameter Validation:
// Middleware to validate that userId is a number
const validateUserId = (req, res, next) => {
const { userId } = req.params;
if (isNaN(userId)) {
return res.status(400).send('Invalid User ID');
}
next(); // Proceed to the next middleware or route handler
};
// Apply middleware to the route
app.get('/users/:userId', validateUserId, (req, res) => {
const { userId } = req.params;
res.send(`Valid User ID: ${userId}`);
});
For a request to /users/123
, it will proceed as normal. But for /users/abc
, it will return Invalid User ID
.
Summary of How to Access Parameters
Route Parameters:
- Defined in the URL pattern.
- Accessed via
req.params
.
app.get('/users/:id', (req, res) => { const id = req.params.id; // Access route parameter res.send(`User ID: ${id}`); });
Query Parameters:
- Appended after the
?
in the URL. - Accessed via
req.query
.
app.get('/search', (req, res) => { const term = req.query.term; // Access query parameter res.send(`Search term: ${term}`); });
- Appended after the
Body Parameters:
- Sent in the body of POST/PUT requests (handled separately with body-parsing middleware).
- Accessed via
req.body
.