node.js - 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')
})
打印什么序列?
解决方案
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 路由器中的一个函数,当被调用时,它会在当前中间件之后执行中间件。
推荐阅读
- vba - Word VBA:扫描文档中的字符串,将其复制到列表中,然后移至下一个匹配项
- python - 如何在 Django 中转换字符串中的列表值?
- c++ - 对和花括号检查
- javascript - 尝试使用 Javascript 在 html 上制作时钟,但我的脚本无法正常工作。时钟实际上并没有运行
- excel - MS Access 2016 中 Excel 工作簿的无链接路径
- confluence - Comala/Confluence - 首次应用 Worfklow 时触发
- xml - 使用 xs:assert XSD 1.1 比较来自不同父级的两个 xml 元素
- reactjs - 如何使用 Next.js 循环获取数组并显示结果
- python - 在python中将构造函数添加到类ordered_dict
- python-3.x - 转换为二进制时出现空格问题