Node.js——Express 中间件使用注意事项
·
Express 中间件使用注意事项
① 一定要在路由之前注册中间件
注意:错误级别的中间件,必须注册在所有路由之后!!!
例:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
throw new Error('服务器内部发生错误')
res.send('home page')
})
// 错误中间件必须注册在所有路由之后
app.use((err, req, res, next) => {
console.log('发生了错误' + err.message)
res.send('Error:' + err.message)
})
app.listen(80, () => {
console.log('express running at http://127.0.0.1')
})
② 客户端发送过来的请求,可以连续调用多个中间件进行处理
③ 执行完中间件的业务代码之后,不要忘记调用 next () 函数
④ 为了防止代码逻辑混乱,调用 next () 函数后不要再写额外的代码
⑤ 连续调用多个中间件时,多个中间件之间,共享 req 和 res 对象
更多推荐


所有评论(0)