router.route(path)

中英双语

返回单个路由的实例,然后您可以使用该实例处理带有可选中间件的 HTTP 动词。使用 router.route() 来避免重复的路由命名,从而避免输入错误。

在上面的 router.param() 示例的基础上,以下代码显示了如何使用 router.route() 来指定各种 HTTP 方法处理程序。

var router = express.Router()

router.param('user_id', function (req, res, next, id) {
  // sample user, would actually fetch from DB, etc...
  req.user = {
    id: id,
    name: 'TJ'
  }
  next()
})

router.route('/users/:user_id')
  .all(function (req, res, next) {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
    next()
  })
  .get(function (req, res, next) {
    res.json(req.user)
  })
  .put(function (req, res, next) {
    // just an example of maybe updating the user
    req.user.name = req.params.name
    // save user ... etc
    res.json(req.user)
  })
  .post(function (req, res, next) {
    next(new Error('not implemented'))
  })
  .delete(function (req, res, next) {
    next(new Error('not implemented'))
  })

此方法重用单个 /users/:user_id 路径并为各种 HTTP 方法添加处理程序。

注意:当您使用 router.route() 时,中间件排序基于路由创建的时间,而不是方法处理程序添加到路由的时间。为此,您可以认为方法处理程序属于添加它们的路由。