1
image.png
image.png
image.png
image.png
注冊為全局生效的中間件
//全局生效的中間件的作用:客戶端發(fā)起的任何請求埂陆,到達服務器之后都會觸發(fā)中間件
const express = require('express')
const app = express()
// 定義一個最簡單的中間件函數(shù)
const mw = function (req, res, next) {
console.log('這是最簡單的中間件函數(shù)')
// 把流轉(zhuǎn)關(guān)系效扫,轉(zhuǎn)交給下一個中間件或路由
next()
}
// // 將 mw 注冊為全局生效的中間件
app.use(mw)
// 先打印這是最簡單的中間件函數(shù)
//再打印届囚,調(diào)用了 / 這個路由
app.get('/', (req, res) => {
console.log('調(diào)用了 / 這個路由')
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