1.創(chuàng)建最基本的中間件
const express = require('express');
const send = require('send');
const app = express()
const mw = function (req, res, next) {
console.log('middleware');
// 一定要調(diào)用next() 把流轉(zhuǎn)關(guān)系交給下一個(gè)中間件或路由
next()
}
app.listen(80, () => {
console.log('express server running at ');
})
2.全局生效的中間件
客戶端發(fā)起的任何請求,到達(dá)服務(wù)器之后,都會(huì)觸發(fā)的中間件
const express = require('express');
const send = require('send');
const app = express()
const mw = (req, res, next) => {
console.log('middleware');
// 一定要調(diào)用next() 把流轉(zhuǎn)關(guān)系交給下一個(gè)中間件或路由
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 ');
})
多個(gè)局部生效的中間件
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.中間件注意事項(xiàng)
中間件必須在路由之前注冊
?
6.中間件分類
- 應(yīng)用中間件
- 路由中間件
- 錯(cuò)誤級別中間件
???????????? 錯(cuò)誤級別中間件必須在所有路由之后
- 內(nèi)置中間件
舉例:express.json()文章來源:http://www.zghlxwxcb.cn/news/detail-645194.html
const express = require('express');
const send = require('send');
const app = express()
// 配置解析表單數(shù)據(jù)的中間件
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文章來源地址http://www.zghlxwxcb.cn/news/detail-645194.html
到了這里,關(guān)于Express中間件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!