?
Ce document utilise Manuel du site Web PHP chinois Libérer
Express是一種路由和中間件Web框架,它具有最小的功能:Express應(yīng)用本質(zhì)上是一系列中間件功能調(diào)用。
中間件功能是可以訪問(wèn)請(qǐng)求對(duì)象(req
),響應(yīng)對(duì)象(res
)以及應(yīng)用程序請(qǐng)求 - 響應(yīng)周期中的下一個(gè)中間件功能的函數(shù)。下一個(gè)中間件函數(shù)通常用名為next
的變量表示。
中間件功能可以執(zhí)行以下任務(wù):
執(zhí)行任何代碼。
對(duì)請(qǐng)求和響應(yīng)對(duì)象進(jìn)行更改。
結(jié)束請(qǐng)求 - 響應(yīng)循環(huán)。
調(diào)用堆棧中的下一個(gè)中間件功能。
如果當(dāng)前的中間件功能沒(méi)有結(jié)束請(qǐng)求 - 響應(yīng)周期,則它必須調(diào)用next()
以將控制傳遞給下一個(gè)中間件功能。否則,請(qǐng)求將被掛起。
Express應(yīng)用程序可以使用以下類(lèi)型的中間件:
Application-level middleware
路由器級(jí)中間件
錯(cuò)誤處理中間件
內(nèi)置中間件
第三方中間件
您可以使用可選的裝載路徑加載應(yīng)用程序級(jí)別和路由器級(jí)別的中間件。您還可以將一系列中間件功能一起加載,從而在掛載點(diǎn)處創(chuàng)建中間件系統(tǒng)的子堆棧。
使用app.use()
and app.METHOD()
函數(shù)將應(yīng)用程序級(jí)中間件綁定到應(yīng)用程序?qū)ο蟮膶?shí)例,其中METHOD
以小寫(xiě)形式是中間件函數(shù)處理的請(qǐng)求的HTTP方法(例如GET,PUT或POST)。
這個(gè)例子顯示了沒(méi)有安裝路徑的中間件功能。每次應(yīng)用程序收到請(qǐng)求時(shí)都會(huì)執(zhí)行該功能。
var app = express()app.use(function (req, res, next) { console.log('Time:', Date.now()) next()})
此示例顯示/user/:id
路徑上安裝的中間件功能。該函數(shù)針對(duì)/user/:id
路徑上的任何類(lèi)型的HTTP請(qǐng)求執(zhí)行。
app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method) next()})
這個(gè)例子顯示了一個(gè)路由及其處理函數(shù)(中間件系統(tǒng))。該函數(shù)處理對(duì)/user/:id
路徑的GET請(qǐng)求。
app.get('/user/:id', function (req, res, next) { res.send('USER')})
下面是一個(gè)在裝載點(diǎn)加載一系列中間件功能的例子,帶有裝載路徑。它演示了一個(gè)中間件子堆棧,用于打印任何類(lèi)型的HTTP請(qǐng)求到/user/:id
路徑的請(qǐng)求信息。
app.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next()}, function (req, res, next) { console.log('Request Type:', req.method) next()})
路由處理程序使您能夠?yàn)槁窂蕉x多個(gè)路由。下面的示例為GET請(qǐng)求定義了兩個(gè)/user/:id
路徑。第二條路由不會(huì)引起任何問(wèn)題,但它不會(huì)被調(diào)用,因?yàn)榈谝粭l路由結(jié)束了請(qǐng)求 - 響應(yīng)周期。
此示例顯示處理GET請(qǐng)求到/user/:id
路徑的中間件子堆棧。
app.get('/user/:id', function (req, res, next) { console.log('ID:', req.params.id) next()}, function (req, res, next) { res.send('User Info')})// handler for the /user/:id path, which prints the user IDapp.get('/user/:id', function (req, res, next) { res.end(req.params.id)})
要跳過(guò)路由器中間件堆棧中的其余中間件功能,請(qǐng)調(diào)用next('route')
以將控制權(quán)傳遞給下一個(gè)路由。注:next('route')
僅適用于使用app.METHOD()
或router.METHOD()
功能加載的中間件功能。
此示例顯示處理GET請(qǐng)求到/user/:id
路徑的中間件子堆棧。
app.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next()}, function (req, res, next) { // render a regular page res.render('regular')})// handler for the /user/:id path, which renders a special pageapp.get('/user/:id', function (req, res, next) { res.render('special')})
路由器級(jí)中間件的工作方式與應(yīng)用級(jí)中間件的工作方式相同,只是它綁定到一個(gè)實(shí)例express.Router()
。
var router = express.Router()
使用router.use()
和router.METHOD()
函數(shù)加載路由器級(jí)中間件。
以下示例代碼通過(guò)使用路由器級(jí)中間件來(lái)復(fù)制上面顯示的用于應(yīng)用程序級(jí)中間件的中間件系統(tǒng):
var app = express()var router = express.Router()// a middleware function with no mount path. This code is executed for every request to the routerrouter.use(function (req, res, next) { console.log('Time:', Date.now()) next()})// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id pathrouter.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next()}, function (req, res, next) { console.log('Request Type:', req.method) next()})// a middleware sub-stack that handles GET requests to the /user/:id pathrouter.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next router if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next()}, function (req, res, next) { // render a regular page res.render('regular')})// handler for the /user/:id path, which renders a special pagerouter.get('/user/:id', function (req, res, next) { console.log(req.params.id) res.render('special')})// mount the router on the appapp.use('/', router)
要跳過(guò)路由器的其他中間件功能,請(qǐng)調(diào)用next('router')
以將控制權(quán)從路由器實(shí)例中退出。
此示例顯示處理GET請(qǐng)求到/user/:id
路徑的中間件子堆棧。
var app = express()var router = express.Router()// predicate the router with a check and bail out when neededrouter.use(function (req, res, next) { if (!req.headers['x-auth']) return next('router') next()})router.get('/', function (req, res) { res.send('hello, user!')})// use the router and 401 anything falling throughapp.use('/admin', router, function (req, res) { res.sendStatus(401)})
錯(cuò)誤處理中間件始終需要四個(gè)參數(shù)。您必須提供四個(gè)參數(shù)來(lái)將其標(biāo)識(shí)為錯(cuò)誤處理中間件功能。即使您不需要使用該next
對(duì)象,也必須指定它以維護(hù)簽名。否則,該next
對(duì)象將被解釋為常規(guī)中間件,并且將無(wú)法處理錯(cuò)誤。
使用與其他中間件功能相同的方式定義錯(cuò)誤處理中間件函數(shù),除了使用四個(gè)參數(shù)而不是三個(gè)參數(shù),特別是使用簽名(err, req, res, next)
):
app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!')})
有關(guān)錯(cuò)誤處理中間件的詳細(xì)信息,請(qǐng)參閱:錯(cuò)誤處理。
從版本4.x開(kāi)始,Express不再依賴(lài)于Connect。Express以前包含的中間件功能現(xiàn)在處于獨(dú)立的模塊中; 請(qǐng)參閱中間件功能列表。
Express具有以下內(nèi)置中間件功能:
express.static提供靜態(tài)資產(chǎn),如HTML文件,圖像等。
express.json使用JSON有效負(fù)載分析傳入的請(qǐng)求。注:適用于Express 4.16.0+
express.urlencoded使用URL編碼的有效負(fù)載分析傳入的請(qǐng)求。注:適用于Express 4.16.0+
使用第三方中間件為Express應(yīng)用程序添加功能。
為所需的功能安裝Node.js模塊,然后將其加載到應(yīng)用程序的應(yīng)用程序級(jí)別或路由器級(jí)別。
以下示例說(shuō)明如何安裝和加載Cookie解析中間件功能cookie-parser
。
$ npm install cookie-parser
var express = require('express')var app = express()var cookieParser = require('cookie-parser') // load the cookie-parsing middlewareapp.use(cookieParser())