Say I have file1.js:
import Router from "express-promise-router";
export const router1 = Router();
router1.get("/", async (req, res) => {
// I want to get here :id from router2 in file2
})
And file2.js (in the same directory for simplicity):
import Router from "express-promise-router";
import { router1 } from "./file1";
export const router2 = Router();
router2.use("/:id/path", router1);
I want to use /:id from file2.js in file1.js (see my comment in example code).
How can I do that?
In other words, how can I percolate '/:something' parameter down the routers chain?
Note - this doesn't work:
router1.get("/", async (req, res) => {
const { params: {id} } = req;
})
I found the answer.
From express api:

So should add the option mergeParams set to true when declaring the router handler.
In general:
const router = express.Router({mergeParams: true});.
For the question's example code in file1.js:
import Router from "express-promise-router";
export const router1 = Router({mergeParams: true});
router1.get("/", async (req, res) => {
const { params: {id} } = req; // now this works
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With