嵌套路由器不会 return 下一个值为 'route' 的回调

Nested router doesn't return next callback with value of 'route'

我正在为中间件构建一个处理程序,我发现当你 return 将 route 字符串作为 next 回调的参数时,它的值是 null.

示例如下:

var express = require('express')
var app = express()

app.use('/', function (req, res, next) {
  var router = express.Router()
  router.use(function (req, res, next) {
    return next('route')
  })
  return router(req, res, function (nextValue) {
    console.log('// value of next')
    console.log(nextValue)
    return next(nextValue)
  })
})

app.use('/', function (req, res, next) {
  return res.send('hi')
})

module.exports = app

这意味着您不能像这样传递下一个处理程序:

app.use('/', function (req, res, next) {
  var router = express.Router()
  router.use(function (req, res, next) {
    return next('route')
  })
  return router(req, res, next)
})

我知道这看起来很多余,因为你可以这样做:

app.use('/', function (req, res, next) {
   return next('route')
})

但是我正在构建一个需要以这种方式使用嵌套中间件的库。似乎我唯一的选择是使用不同的字符串,因为如果我这样做:

  router.use(function (req, res, next) {
    return next('anystring')
  })

next 回调确实为 nextValue 提供 anystring

为什么字符串 route 不通过嵌套中间件传播?

express 不 return route 这似乎是有意义的,因为在那个时候 route 那条 route 已经完成了。

首先。所以我改用 .all 。即使那样 return 字符串 "route" 也不行。所以我需要在最后向路由器中注入一些中间件。如果 nextRoute 的值未更新,那么 next('route') 在中间件堆栈期间的某个时间被调用,我可以将它向上传播到父中间件。

我发现我必须在最后注入一个中间件到

app.use(function (req, res, next) {
  var router = express.Router()
  var nextRoute = true
  router.all('/', [
    function (req, res, next) {
      return next('route')
    },
    function (req, res, next) {
      nextRoute = false
      return res.send('hi')
    },
  ])
  return router(req, res, function (nextValue) {
    if (nextRoute && !nextValue) return next('route')
    return next(nextValue)
  })
})

app.use('/', function (req, res, next) {
  return res.send('hi')
})

这允许我的 middleware-nest 模块工作:

var _ = require('lodash')
var express = require('express')

/** Allow for middleware to run from within middleware. */
function main (req, res, next, Router, middleware) {
  var args = _.values(arguments)
  middleware = _.flatten([_.slice(args, 4)])
  Router = (Router) ? Router : express.Router
  var router = Router()
  var nextRoute = true
  middleware.push(function (req, res, next) {
    nextRoute = false
    return next()
  })
  router.all('*', middleware)
  return router(req, res, function (nextValue) {
    if (nextRoute && !nextValue) return next('route')
    return next(nextValue)
  })
}

main.applyRouter = function (Router) {
  Router = (Router) ? Router : express.Router
  return function () {
    var args = _.values(arguments)
    args.splice(3, 0, Router)
    return main.apply(null, args)
  }
}

module.exports = main