1.创建最基本的中间件
const express = require('express');
const send = require('send');const app = express()const mw = function (req, res, next) {console.log('middleware');// 一定要调用next() 把流转关系交给下一个中间件或路由next()
}app.listen(80, () => {console.log('express server running at ');})
2.全局生效的中间件
客户端发起的任何请求,到达服务器之后,都会触发的中间件
const express = require('express');
const send = require('send');const app = express()const mw = (req, res, next) => {console.log('middleware');// 一定要调用next() 把流转关系交给下一个中间件或路由next()
}// 将mw注册为全局生效的中间件
app.use(mw)app.get('/', (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})
3.局部生效的中间件
const express = require('express');
const send = require('send');const app = express()const mw1 = (req, res, next) => {console.log('mw1');next()
}// 局部生效
app.get('/', mw1, (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})
多个局部生效的中间件
const express = require('express');
const send = require('send');const app = express()const mw1 = (req, res, next) => {console.log('mw1');next()
}
const mw2 = (req, res, next) => {console.log('mw2');next()
}
// 局部生效
// app.get('/', [mw1,mw2], (req, res) => { 也行
app.get('/', mw1,mw2, (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})
4.中间件的作用
5.中间件注意事项
中间件必须在路由之前注册
6.中间件分类
- 应用中间件
- 路由中间件
- 错误级别中间件
错误级别中间件必须在所有路由之后
- 内置中间件
举例:express.json()
const express = require('express');
const send = require('send');
const app = express()// 配置解析表单数据的中间件
app.use(express.json())app.get('/', (req, res) => {console.log(req.header, req.body);res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})
7.自定义中间件
08.中间件-自定义中间件_哔哩哔哩_bilibili