Express v4:如何在参数中间件之前运行特定于路由的中间件

Express v4: How do I run route-specific middleware before param middleware?

本文关键字:中间件 于路由 路由 运行 v4 参数 Express      更新时间:2023-09-26

长话短说,我有一个相当奇怪的路由场景,我需要在调用参数中间件之前调用中间件:

router.param('foo', function (req, res, next, param) {
  // Get the param value
  ...
  next()
})
router.route('/:foo')
  .all(function (req, res, next) {
    // I want to run this before the router.param middleware
    // but I don't want to run this on /:foo/bar
    ...
    next()
  })
  .get(function (req, res, next) {
    // Run this after the router.param middleware
    ...
    res.send('foo')
  })
router.route('/:foo/bar')
  .get(function (req, res, next) {
    // Run this after the router.param middleware
    ...
    res.send('bar')
  })

现在,我明白为什么参数中间件通常首先运行,但是有没有办法解决这个问题?

我尝试在没有路径的情况下使用router.use

router.use(function (req, res, next) {
  // I want to run this before the router.param middleware
  // but I don't want to run this on /:foo/bar
  ...
  next()
})

。并在 router.param 中间件之前调用它,但随后它也会被调用用于/:foo/bar

最后,如果我将router.use与这样的路径一起使用

router.use('/:foo', function (req, res, next) {
  // I want to run this before the router.param middleware
  // but I don't want to run this on /:foo/bar
  ...
  next()
})

。路由器.参数中间件首先被调用(如您所料)。

有没有办法做到这一点?

我绝不是正则表达式的专家,但您可以使用正则表达式来匹配路由。这将适用于您的特定用例,尽管可能有更好的方法。

router.use(/^'/[^'/]*$/, function(req, res, next) {
});