ExpressJS req.params在嵌套路由器中为空

时间:2015-03-17 15:07:57

标签: javascript node.js express

我使用的路由设置使用了我的' api'文件夹的目录结构,以直观地设置路线。但是,如果我使用文件夹名称来表示路由参数,则控制器中的req.params未定义。

有问题的路线是:

GET /api/google/accounts/:account_id/analytics/profiles/

这是我的路由加载器。它基本上在api文件夹上执行一个glob,查找名为routes.js的文件,并在适当的路径上执行app.use(从文件夹结构中确定)。

  // load routers
  files = glob.sync("api/**/routes.js");

  console.log(files);
  // [ 'api/campaigns/routes.js',
  //   'api/google/accounts/:account_id/analytics/profiles/routes.js',
  //   'api/google/accounts/routes.js',
  //   'api/google/urls/routes.js',
  //   'api/users/routes.js' ]

  // use each router on the appropriate route
  for(var i=0;i<files.length;i++) {

    route  = "/" + files[i].split("/routes.js")[0];

    console.log(route);
    // '/api/google/accounts/:account_id/analytics/profiles'

    router = require(path.join(__dirname, files[i]))(config);
    routes = router.stack;
    app.use(route, router);

    // list all registered routes for this 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);
    }
  }

&#39; api&#39;文件夹结构是:

./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

在上面的循环中,routeDebug是debug npm包的包装器。输出是:

  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

因此我们可以看到有问题的路线正在按预期设置。但是req.params是未定义的。其他路线没有这个问题。

为什么req.params仅为此特定路线为空?有没有比使用文件夹作为路由参数更好的方法来构建这些嵌套路由?

编辑:我希望问题源于嵌套路由器无法访问父路由器&#39; PARAMS。

Rest with Express.js nested router

但是,按照建议设置子路由器也没有帮助。

var router = require("express").Router({mergeParams: true});
// no difference

1 个答案:

答案 0 :(得分:6)

结果是mergeParams was not added to Express until 4.5.0;我的项目仍在4.2.0。更新到4.5.0并将{mergeParams: true}传递给子路由器解决了这个问题。有关更多详细信息,请参阅此类似问题:

Rest with Express.js nested router