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

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

本文关键字:route 回调 路由器 返回 下一个 嵌套      更新时间:2023-09-26

我正在为中间件构建一个处理程序,我发现当您返回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来说,不返回route似乎是有意义的,因为在该点路由,该路由已经完成。

首先.use不支持next('route')。所以我用.all代替。即使这样也不会返回字符串"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