express 中间件的定义与使用

235 阅读2分钟

1、中间件的定义

多个中间件之间, 共享同一份 req 和 res。基于这样的特性,我们可以在上游的中间件中, 统一为 req 或 res 对象添 加自定义的属性或方法,供下游的中间件或路由进行使用

定义全局中间件

const express = require('express')
const router = express.Router()
const app = express()
// 定义中间件1
const mw1 = (req, res, next) => {
    console.log('中间件1')
    next()
}
​
// 定义中间件2
const mw2 = (req, res, next) => {
    console.log('中间件2')
    next()
}
app.use(mw1)//注册中间件1
app.use(mw2)//注册中间件2
​
router.get('/user', (req, res) => {
    console.log('user 路由')
    res.send('user')
})
​
router.get('/', (req, res) => {
    console.log('/ 路由')
    res.send('/')
})
// 输出 
// 中间件1
// 中间件2  
// user 路由

定义局部中间件:只在局部生效

// 定义中间件1
const mw1 = (req, res, next) => {
    console.log('中间件1')
    next()
}
// 定义中间件2
const mw2 = (req, res, next) => {
    console.log('中间件2')
    next()
}
app.use(mw1)//注册中间件1
app.use(mw2)//注册中间件2
​
router.get('/user',mw1,mw2, (req, res) => {
    console.log('user 路由')
    res.send('user')
})

使用中间件的注意事项:

① 一定要在路由之前注册中间件

② 客户端发送过来的请求, 可以连续调用多个中间件进行处理

③ 执行完中间件的业务代码之后, 不要忘记调用 next() 函数

④ 为了防止代码逻辑混乱,调用 next() 函数后不要再写额外的代码

⑤ 连续调用多个中间件时,多个中间件之间, 共享 req 和 res 对象

2、中间件的分类

大致可以分为五类:应用级别的中间件、路由级别的中间件、错误级别的中间件、Express内置中间件、第三方中间件

错误级别中间件的作用:专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题。

格式:错误级别中间件的 function 处理函数中, 必须有 4 个形参,形参顺序从前到后,分别是 (err, req, res, next)

const mw  = (err,req,res,next)=>{
    console.log(err)
    res.send('...')
}
app.use(mw)
// 错误级别的中间件必须注册在路由中间件之后

内置中间件主要有三个

app.use(express,staic('/files'))//托管静态资源
​
app.use(express.json())//将前端传来的json数据进行解析 data数据
req.body()// 可以获取到解析好的json数据
​
app.use(express.urlencoded({extended:false}))//解析前端的表单数据

\