打赏

express 中间件

1、路由可以有多个回调

实际上,路由方法可以具有多个回调函数作为参数。 对于多个回调函数,重要的是提供next作为回调函数的参数,然后在函数体内调用next()将控制权移交给下一个回调。

2、一个路由有多个回调示例

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})

3、数组形式

var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])

4、next

中间件通过next实现。

但是express对异步实现不好,在处理异步问题时中间件容易有问题。

原因是:异步事件在另外一个事件队列,上一个next函数处理不到。

posted @ 2020-10-05 23:31  孟繁贵  阅读(175)  评论(0编辑  收藏  举报
TOP