Topic 40 of 55
req.params
Overview
Route parameters are named URL segments used to capture dynamic values (like an ID). They are defined in the route path with a colon `:` and accessed via the `req.params` object.
Syntax
javascript
// Define a dynamic parameter by prefixing it with a colon
app.get('/users/:userId', (req, res) => {
// If URL is /users/42
console.log(req.params); // { userId: '42' }
res.send(`Looking up user with ID ${req.params.userId}`);
});
// Multiple parameters
app.get('/flights/:from/:to', (req, res) => {
// If URL is /flights/JFK/LAX
const { from, to } = req.params;
res.send(`Searching flights from ${from} to ${to}`);
});Common Pitfalls
- Values in `req.params` are ALWAYS strings. If you need a number (e.g., for a database lookup), you must parse it: `parseInt(req.params.id)`.
- Beware of route conflicts: `app.get('/users/new')` must be defined BEFORE `app.get('/users/:id')`. Otherwise, Express will think 'new' is the ID!
Real-World Example
A standard API endpoint fetching a resource by ID:
example
javascript
app.get('/api/articles/:articleId', async (req, res) => {
try {
// 1. Extract the ID from the URL
const id = req.params.articleId;
// 2. Look it up in the database
const article = await db.findById(id);
// 3. Handle 'Not Found' gracefully
if (!article) {
return res.status(404).json({ error: "Article not found" });
}
// 4. Send the result
res.json(article);
} catch (err) {
res.status(500).json({ error: "Server error" });
}
});