4

i'd like to nest resources like the below eg.

/// fileA.js
app.use('/dashboards/:dashboard_id/teams', teams);
[...]

///teams.js
router.get('/', function(req, res, next) {
[...]
}

but I can't get the req.params["dashboard_id"] parameter in teams because it seems it is already substituted with the parameter value. I've tried to baypass the problem by calling an intermediate function and pass somewhere the parameter but I can't figure out where ... Do you have an answer? Thanks, Franco

franco
  • 133
  • 2
  • 10

3 Answers3

4

You may try this solution:

//declare a function that will pass primary router's params to the request
var passPrimaryParams = function(req, res, next) {
    req.primaryParams = req.params;
    next();
}

/// fileA.js
app.use('/dashboards/:dashboard_id/teams', passPrimaryParams);
app.use('/dashboards/:dashboard_id/teams', teams);

///teams.js
router.get('/', function(req, res, next) {
    var dashboardId = req.primaryParams['dashboard_id'];  //should work now
    //here you may also use req.params -- current router's params
}
Oleg
  • 22,300
  • 9
  • 68
  • 84
4

Using Express 4.0.0 or above at the time of this writing:

To make the router understand nested resources with variables you will need create and bind a new router using app.use for every base path.

//creates a new router
var dashboardRouter = express.router();

//bind your route
dashboardRouter.get("/:dashboard_id/teams", teams);

//bind to application router
app.use('/dashboards', dashboardRouter);

This way Express will see the first part of the path and go to the /dashboards route, which has the :dashboard_id/teams path.

Kelz
  • 494
  • 4
  • 9
  • This will require us to bind a route for each route in the parent router, which is not ideal. Much better to use router.use if possible. – Mild Fuzz Oct 29 '15 at 08:27
1

You can use the mergeParams option here

// fileA.js
app.use('/dashboards/:dashboard_id/teams', teams);

// teams.js
const router = express.Router({ mergeParams: true })
router.get('/', function(req, res, next) {
  // you will have access to req.params.dashboard_id here
}

You can also see this answer: Rest with Express.js nested router

Danny Sullivan
  • 3,626
  • 3
  • 30
  • 39