Express路由将variables传递给所需的文件

我试图让所有我的控制器调用一个名为索引的文件,所以我不只是build立在一个文件中的所有快递路线。

因此我的index.js看起来像:

//imports and stuff router.use('/auth', require('./auth')) router.use('/users', require('./users')) router.use('/:world_id/villages', require('./villages')) //export router 

然后我有auth.js和users.js文件。

auth.js:

 router.route('/register') .post(function(req, res) { //register the user }) 

users.js:

 router.route('/:user_id') //GET user profile .get(function(req, res){ // Use the req.params.userId to get the user by Id }) 

而这两者都适用于这两个。 访问/api/auth/register/api/users/:user_id按预期工作。

但是,当试图去/api/{world_id}/villages这不会如预期的那样,因为world_id参数不会传递到文件处理它是villages.js

villages.js:

 router.route('/') //GET all villages of the current world (world_id) .get(function(req, res){ // Use the req.params.world_id to get it... but this is undefined :( }) 

我怎么能有这个文件结构,所以我的控制器不会混乱,同时,传递这个参数到控制器文件,以便它可以使用它,即使路由是('/')?

在子路由器中使任何参数可见的唯一方法是在那里定义它。 所以在你的例子中

 router.route('/:world_id/villages/') //GET all villages of the current world (world_id) .get(function(req, res){ // req.params.world_id is set }) // ... app.use('/', router);