?
This document uses PHP Chinese website manual Release
Express是一種路由和中間件Web框架,它具有最小的功能:Express應用本質上是一系列中間件功能調用。
中間件功能是可以訪問請求對象(req
),響應對象(res
)以及應用程序請求 - 響應周期中的下一個中間件功能的函數(shù)。下一個中間件函數(shù)通常用名為next
的變量表示。
中間件功能可以執(zhí)行以下任務:
執(zhí)行任何代碼。
對請求和響應對象進行更改。
結束請求 - 響應循環(huán)。
調用堆棧中的下一個中間件功能。
如果當前的中間件功能沒有結束請求 - 響應周期,則它必須調用next()
以將控制傳遞給下一個中間件功能。否則,請求將被掛起。
Express應用程序可以使用以下類型的中間件:
Application-level middleware
路由器級中間件
錯誤處理中間件
內置中間件
第三方中間件
您可以使用可選的裝載路徑加載應用程序級別和路由器級別的中間件。您還可以將一系列中間件功能一起加載,從而在掛載點處創(chuàng)建中間件系統(tǒng)的子堆棧。
使用app.use()
and app.METHOD()
函數(shù)將應用程序級中間件綁定到應用程序對象的實例,其中METHOD
以小寫形式是中間件函數(shù)處理的請求的HTTP方法(例如GET,PUT或POST)。
這個例子顯示了沒有安裝路徑的中間件功能。每次應用程序收到請求時都會執(zhí)行該功能。
var app = express()app.use(function (req, res, next) { console.log('Time:', Date.now()) next()})
此示例顯示/user/:id
路徑上安裝的中間件功能。該函數(shù)針對/user/:id
路徑上的任何類型的HTTP請求執(zhí)行。
app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method) next()})
這個例子顯示了一個路由及其處理函數(shù)(中間件系統(tǒng))。該函數(shù)處理對/user/:id
路徑的GET請求。
app.get('/user/:id', function (req, res, next) { res.send('USER')})
下面是一個在裝載點加載一系列中間件功能的例子,帶有裝載路徑。它演示了一個中間件子堆棧,用于打印任何類型的HTTP請求到/user/:id
路徑的請求信息。
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()})
路由處理程序使您能夠為路徑定義多個路由。下面的示例為GET請求定義了兩個/user/:id
路徑。第二條路由不會引起任何問題,但它不會被調用,因為第一條路由結束了請求 - 響應周期。
此示例顯示處理GET請求到/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)})
要跳過路由器中間件堆棧中的其余中間件功能,請調用next('route')
以將控制權傳遞給下一個路由。注:next('route')
僅適用于使用app.METHOD()
或router.METHOD()
功能加載的中間件功能。
此示例顯示處理GET請求到/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')})
路由器級中間件的工作方式與應用級中間件的工作方式相同,只是它綁定到一個實例express.Router()
。
var router = express.Router()
使用router.use()
和router.METHOD()
函數(shù)加載路由器級中間件。
以下示例代碼通過使用路由器級中間件來復制上面顯示的用于應用程序級中間件的中間件系統(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)
要跳過路由器的其他中間件功能,請調用next('router')
以將控制權從路由器實例中退出。
此示例顯示處理GET請求到/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)})
錯誤處理中間件始終需要四個參數(shù)。您必須提供四個參數(shù)來將其標識為錯誤處理中間件功能。即使您不需要使用該next
對象,也必須指定它以維護簽名。否則,該next
對象將被解釋為常規(guī)中間件,并且將無法處理錯誤。
使用與其他中間件功能相同的方式定義錯誤處理中間件函數(shù),除了使用四個參數(shù)而不是三個參數(shù),特別是使用簽名(err, req, res, next)
):
app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!')})
有關錯誤處理中間件的詳細信息,請參閱:錯誤處理。
從版本4.x開始,Express不再依賴于Connect。Express以前包含的中間件功能現(xiàn)在處于獨立的模塊中; 請參閱中間件功能列表。
Express具有以下內置中間件功能:
express.static提供靜態(tài)資產,如HTML文件,圖像等。
express.json使用JSON有效負載分析傳入的請求。注:適用于Express 4.16.0+
express.urlencoded使用URL編碼的有效負載分析傳入的請求。注:適用于Express 4.16.0+
使用第三方中間件為Express應用程序添加功能。
為所需的功能安裝Node.js模塊,然后將其加載到應用程序的應用程序級別或路由器級別。
以下示例說明如何安裝和加載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())