Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get req.param id from route above

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading