Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 787
franco Avatar asked Jan 10 '23 02:01

franco


2 Answers

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
}
like image 69
Oleg Avatar answered Jan 16 '23 20:01

Oleg


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.

like image 23
Kelz Avatar answered Jan 16 '23 20:01

Kelz