什么是嵌套快速路由的 DRY 方法

What is the DRY approach for Nested Express Routes

我想要一个 api 允许获取一个人的嵌套属性

router.get('/person/:id', fun.. router.get('/person/:id/name, fun... router.get('/person/:id/address, fun...

都是同一个猫鼬方案的对象。查找 person 对象的最佳方法是什么?我觉得我应该使用 router.use(/person/:id) 来查看这个人并以某种方式传递它。

勾选app.param(),例如:

router.param('id', function(req, res, next, id) {
  Person.find(id, function(err, person) {
    if (err)next(err);
    else if (person) {
      req.person = person;
      next();
    } else {
      next(new Error('failed to load person'));
    }
  });
});

router.get('/person/:id', function() { /* ... */});
router.get('/person/:id/name', function() { /* ... */});
router.get('/person/:id/address', function() { /* ... */});

然后您可以从 req.person.

访问您的 Person 对象