一、Express中间件的五大分类
Express官方把常见的中间件用法,分成了5大类,分别是:
1.应用级别的中间件
通过app.use() 或 app.get() 或
app.post(),绑定到app实例上的中间件,叫做应用级别的中间件
//应用级别的全局中间件
app.use(function(req,res,next){
console.log('我是全局中间件')
next()
})
let jubu = function(req,res,next){
console.log('我是局部中间件')
next()
}
//应用级别的局部中间件
app.get('/user',jubu, (req, res) => {
console.log('先经过局部中间件才打印我')
//向客户端发送JSON对象
res.send({
name: 'doraMiu', age: '20', gender: '女' })
})
2.路由级别的中间件
绑定到**express.Router()**实例上的中间件,叫做路由级别的中间件。它的用法与应用级别的中间件没有任何区别。
只不过,应用级别中间件是绑定到app实例上,路由级别中间件是绑定到Router实例上
const app = express()
const router = express.Router()
//路由级别的中间件
router.use(function(req,res,next){
console