Let’s say I have on file A the next expression;
router.use("/:id/address", Address);
And on file B
router.get("/", (req, res) => {
const id = req.params.id;
the id gives undefined, is it possible to get it through this configuration?
If not that’s alright but it would be great to add since it can help to tidy up the code
>Solution :
In your Address router file (File B), create a new router with the mergeParams option set to true:
const router = express.router({ mergeParams: true });
router.get("/", (req, res) => {
const id = req.params.id;
console.log(id) //should show the id now.
});
By setting mergeParams to true, you tell Express to merge the parent route’s parameters with the child route’s parameters. This way, you can access the id parameter in the child route handler.
Read more here: https://expressjs.com/en/api.html