Route Parameters and Query Strings
Veeg om het menu te tonen
When building web applications with Express.js, you often need to handle URLs that contain dynamic values or accept optional input from the client. Express.js provides two main mechanisms for this: route parameters and query strings.
A route parameter is a variable part of the URL path. It is defined in the route path using a colon (:) followed by the parameter name. For example, you might define a route like /users/:id to handle requests for different users based on their unique ID. When a request matches this pattern, Express.js makes the value available on the req.params object.
A query string consists of key-value pairs appended to the end of a URL after a question mark (?). Query strings are commonly used to provide optional information to the server, such as search filters or pagination settings. In Express.js, query string values are available on the req.query object.
Here is an example that demonstrates both route parameters and query strings in action:
// Example route with a route parameter
app.get('/users/:id', (req, res) => {
// Access route parameter
const userId = req.params.id;
// Access query string parameters
const showDetails = req.query.details;
res.send(`User ID: ${userId}, Show details: ${showDetails}`);
});
In this example, when a client sends a GET request to /users/42?details=true, Express.js will extract the route parameter id with a value of "42" and the query string parameter details with a value of "true". The handler uses req.params.id to access the route parameter and req.query.details to access the query string value.
To extract and use route parameters and query strings in your request handlers, follow these steps:
- Define a route path with a colon and parameter name for each dynamic segment you want to capture;
- Use the
req.paramsobject to access the route parameters inside your handler function; - Use the
req.queryobject to access query string parameters, which are always strings or undefined if not provided; - Combine both mechanisms as needed to build flexible and dynamic endpoints.
For instance, if you define a route as /products/:productId, and a client requests /products/123?color=red&size=large, you will find req.params.productId === "123", req.query.color === "red", and req.query.size === "large". This makes it easy to write handlers that can fetch resources by ID and also filter or modify the response based on optional client input.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.