使用Express对带前缀的参数进行分解

时间:2015-06-25 16:51:57

标签: javascript node.js express

我的Express路由器有几条路线:

router
.post('/:id/foo/*', func1)
.get('/:id/bar/*', func2)
.post('/:id/foobar/*', func3);

所有这些路由共享“/:id /”前缀,我想知道是否有更紧凑和优雅的方式来编写它。

目标是编写类似的内容:

router
<something to capture de /:id/ and pass the subroutes to the following functions>
.post('/foo/*', func1)
.get('/bar/*', func2)
.post('/foobar/*', func3)

是错误/良好/可行的想法吗?

1 个答案:

答案 0 :(得分:2)

在Express 4.5+中,您可以使用Router

// mergeParams allows parent params to be passed down to child routes
var router = express.Router({
  mergeParams: true
});

router
  .post('/foo/*', func1)
  .get('/bar/*', func2)
  .post('/foobar/*', func3);

// Mount router at `/:id`
app.use('/:id', router);

如果你想在其他中间件之前预处理id param,你也可以使用app.param,这也会使得从父节点到子节点的params合并无效。

// No need to mergeParams as `res.locals.id` will be populated
//  by app.param middleware
var router = express.Router();
router
  .post('/foo/*', func1)
  .get('/bar/*', func2)
  .post('/foobar/*', func3);

app.param('id', function(req, res, next, id) {
  // ... do some logic if desired ...
  // assign the id to the res.locals object for downstream middleware
  res.locals.id = id;
  next();
});

app.use('/:id', router);