Reputation: 517
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;
})
Upvotes: 3
Views: 639
Reputation: 517
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
})
Upvotes: 3