I use a routing setup that uses my api folder directory structure to intuitively configure routes. However, in cases where I use the folder name to represent the route parameter, req.params is undefined in the controller.
The route with the problem:
GET /api/google/accounts/:account_id/analytics/profiles/
Here is my route loader. It basically does glob in the api folder, looking for files with a name routes.jsand does app.useon the appropriate route (determined from the folder structure).
files = glob.sync("api/**/routes.js");
console.log(files);
for(var i=0;i<files.length;i++) {
route = "/" + files[i].split("/routes.js")[0];
console.log(route);
router = require(path.join(__dirname, files[i]))(config);
routes = router.stack;
app.use(route, router);
for(var j=0;j<routes.length;j++) {
routeDebug((" " + Object.keys(routes[j].route.methods)[0].toUpperCase()).slice(-6) + " " + route + routes[j].route.path);
}
}
Folder structure "api":
./api
./api/campaigns
./api/campaigns/controller.js
./api/campaigns/model.js
./api/campaigns/routes.js
./api/users
./api/users/controller.js
./api/users/model.js
./api/users/routes.js
./api/google
./api/google/accounts
./api/google/accounts/:account_id
./api/google/accounts/:account_id/analytics
./api/google/accounts/:account_id/analytics/profiles
./api/google/accounts/:account_id/analytics/profiles/controller.js
./api/google/accounts/:account_id/analytics/profiles/routes.js
./api/google/accounts/controller.js
./api/google/accounts/model.js
./api/google/accounts/routes.js
./api/google/urls
./api/google/urls/controller.js
./api/google/urls/routes.js
In the above loop, routeDebug is a wrapper around the debug npm package. Output:
routes GET /api/campaigns/ +0ms
routes POST /api/campaigns/ +2ms
routes GET /api/campaigns/:campaign_id +1ms
routes PUT /api/campaigns/:campaign_id +0ms
routes DELETE /api/campaigns/:campaign_id +0ms
routes GET /api/google/accounts/:account_id/analytics/profiles/ +128ms
routes GET /api/google/accounts/ +4ms
routes POST /api/google/accounts/ +0ms
routes POST /api/google/urls/ +3ms
routes GET /api/users/ +12ms
routes POST /api/users/ +0ms
routes GET /api/users/:user_id +0ms
routes PUT /api/users/:user_id +0ms
routes DELETE /api/users/:user_id +0ms
Thus, we see that this route is configured as expected. But req.params is undefined. Other routes do not have this problem.
req.params ? , ?
EDIT: , , .
Express.js
.
var router = require("express").Router({mergeParams: true});