Q1. What are route parameters in Express?
Route parameters are named URL segments used to capture values at specific positions in the URL.
They are defined with a colon prefix.
Example:
The values are stored in
They are defined with a colon prefix.
Example:
/users/:userId/books/:bookIdThe values are stored in
req.params: { userId: '123', bookId: '456' }.Q2. How do you access route parameters?
Through the
For a route defined as
If you have multiple parameters, they all become properties of
req.params object.For a route defined as
app.get('/products/:id', ...), you access the id with req.params.id.If you have multiple parameters, they all become properties of
req.params.Q3. What are query parameters and how do you access them?
Query parameters come after ? in the URL (e.g.,
They are accessed via
For the example,
Query parameters are optional and used for filtering, sorting, or pagination.
/search?q=express&page=2).They are accessed via
req.query.For the example,
req.query gives { q: 'express', page: '2' }.Query parameters are optional and used for filtering, sorting, or pagination.
Q4. Can route parameters be optional?
In Express, route parameters are required by default.
To make them optional, you need to use a regular expression or define multiple routes.
Alternatively, you can use query parameters for optional values, or use
To make them optional, you need to use a regular expression or define multiple routes.
Alternatively, you can use query parameters for optional values, or use
app.all() with conditional logic.Q5. How do you build dynamic URLs in Express?
You combine static parts with route parameters.
For example,
You can also use regular expressions in route paths for more complex matching, like
For example,
/posts/:postId/comments/:commentId creates a hierarchical structure.You can also use regular expressions in route paths for more complex matching, like
/user/:id(\d+) to match only numeric IDs.