1
image.png
image.png
image.png
image.png
注册为全局生效的中间件
//全局生效的中间件的作用:客户端发起的任何请求,到达服务器之后都会触发中间件
const express = require('express')
const app = express()
// 定义一个最简单的中间件函数
const mw = function (req, res, next) {
console.log('这是最简单的中间件函数')
// 把流转关系,转交给下一个中间件或路由
next()
}
// // 将 mw 注册为全局生效的中间件
app.use(mw)
// 先打印这是最简单的中间件函数
//再打印,调用了 / 这个路由
app.get('/', (req, res) => {
console.log('调用了 / 这个路由')
res.send('Home page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
重点
image.png
体验中间件的作用
const express = require('express')
const app = express()
// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
// 获取到请求到达服务器的时间
const time = Date.now()
// 为 req 对象,挂载自定义属性,从而把时间共享给后面的所有路由
req.startTime = time
next()
})
app.get('/', (req, res) => {
res.send('Home page.' + req.startTime)
})
app.get('/user', (req, res) => {
res.send('User page.' + req.startTime)
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
多个中间件的使用
image.png