首页 > 解决方案 > Express:next() 如何与多个 Route 处理程序一起工作?

问题描述

我是 Express 的新手,我对next()在这种情况下的工作方式感到困惑:

//Route 1
app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id)
  next()
}, function (req, res, next) {
  res.send('User Info')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id)
})

在上面的例子中,执行顺序是什么?理论上,是否res.end(req.params.id)早于res.send('User Info')? (即使 res.end() 将结束请求-响应循环。)next()在这种情况下会做什么?

或者考虑另一种情况:

//Route 1
app.get('/user/:id', function (req, res, next) {
  console.log('1')
  next()
}, function (req, res, next) {
  console.log('2')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  console.log('3')
})

打印什么序列?

标签: node.jsexpress

解决方案


Express 中间件是在向 Express 服务器发出请求的生命周期内执行的函数。每个中间件都可以访问它所附加的每个路由(或路径)的 HTTP 请求和响应。事实上,Express 本身完全受到中间件功能的影响。

中间件函数根据其用法有 2/3/4 个参数,如下所示:

function (error, request, response, next) {}

当路由器激活时,express 将从第一个中间件开始执行,next 用于将执行传递给列表中的后续中间件。

app.get('path', 'middleware 1', 'middleware 2', 'middleware 3', ... so on)

你想了解的案例:

app.get('/user/:id', function (req, res, next) {
  console.log('1')
  next()
}, function (req, res, next) {
  console.log('2')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  console.log('3')
})

您的路由是相同的,express 将始终执行第一个匹配的路由,route 1并将执行使用 next 将执行传递给下一个中间件。o/p 将始终为:

1
2

在上面的例子中,执行顺序是什么?从理论上讲,res.end(req.params.id) 是否比 res.send('User Info') 更早执行?(即使 res.end() 将结束请求-响应循环。)在这种情况下 next() 会做什么?

Route1 将被执行,一旦您发送响应,express 在内部调用 next 来打包响应并发送它。

next函数是 Express 路由器中的一个函数,当被调用时,它会在当前中间件之后执行中间件。


推荐阅读