Nested Dynamic Routes
Provide an example of nested dynamic routes with a parent-child relationship and explain how to access nested query parameters.
import express from 'express';
const app = express();
// Middleware to parse the request body
app.use(express.json());
// Parent route with dynamic parameter :parentId
app.get('/parent/:parentId', (req, res, next) => {
// Access parent dynamic parameter
const parentId = req.params.parentId;
res.send(`Parent ID: ${parentId}`);
next(); // pass control to the next handler
});
// Nested child route with dynamic parameter :childId
app.get('/parent/:parentId/child/:childId', (req, res) => {
// Access parent and child dynamic parameters
const parentId = req.params.parentId;
const childId = req.params.childId;
res.send(`Parent ID: ${parentId}, Child ID: ${childId}`);
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server listening on port ${port}`));
This is an Express.js server example setting up nested dynamic routes. The first GET route handler matches requests to '/parent/:parentId' and extracts the parentId parameter. The second GET route is nested under the first, matching requests to '/parent/:parentId/child/:childId' and extracting both parentId and childId parameters. Note that 'next' is called in the parent route to allow the request to continue to additional route handlers that might match the URL path.