franco
franco

Reputation: 141

Node.js Express nested resources

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

Upvotes: 4

Views: 3087

Answers (3)

Danny Sullivan
Danny Sullivan

Reputation: 3844

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

Upvotes: 1

Kelz
Kelz

Reputation: 494

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.

Upvotes: 4

Oleg
Oleg

Reputation: 23277

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
}

Upvotes: 4

Related Questions