1、express内置的中间件
解析json格式请求体数据
app.use(express.json())
app.use(express.urlencoded())
2、应用级别中间件
全局中间件和局部中间件直接绑定在app的实例上,就叫应用级别中间件
// 全局中间件
app.use(middlieware)
// 局部中间件
app.get('/login', middleware, () => {})
3、路由级别中间件
中间件绑定在路由router上
router.use(middleware)
4、错误级别中间件
在全局项目中捕获异常错误,防止项目报错异常奔溃
app.post('/user/login', (req, res) => {
throw new Error('项目发生了错误')
console.log(req.body)
res.send('登录成功')
})
app.use((err, req, res, next) => {
res.send(err.message)
})
5、第三方中间件body-parser
解析请求体json、url-encode数据
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())