express初步學(xué)習(xí)-中間件

express學(xué)習(xí)——中間件

Express是什么?

Express是一個基于Node.js平臺的web應(yīng)用開發(fā)框架,在Node.js基礎(chǔ)之上擴(kuò)展了web應(yīng)用開發(fā)所需要的基礎(chǔ)功能,從而使得我們開發(fā)Web應(yīng)用更加方便、更加快捷。其中,Express項目的底層由許多的中間件在協(xié)同工作,可以這么說,一個 Express 應(yīng)用就是在調(diào)用各種中間件。

什么是中間件

中間件是一個可訪問請求對象(req)和響應(yīng)對象(res)的函數(shù),在 Express 應(yīng)用的請求-響應(yīng)循環(huán)里,下一個內(nèi)聯(lián)的中間件通常用變量 next 表示。中間件的功能包括:

  1. 執(zhí)行任何代碼。
  2. 修改請求和響應(yīng)對象。
  3. 終結(jié)請求-響應(yīng)循環(huán)。
  4. 調(diào)用堆棧中的下一個中間件。
    注意: 如果當(dāng)前中間件沒有終結(jié)請求-響應(yīng)循環(huán),則必須調(diào)用 next() 方法將控制權(quán)交給下一個中間件,否則請求就會掛起。

中間件的類別

應(yīng)用級中間件

應(yīng)用級別的中間件綁定到express實例,用法是 app.use() 或app.METHOD()
例子:

 此示例顯示了沒有裝載路徑的中間件功能。每次應(yīng)用程序收到請求時都會執(zhí)行該功能。
 var app = express()

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})
此示例顯示了/user/:id路徑上安裝的中間件功能。對/user/:id路徑上的任何類型的HTTP請求執(zhí)行該函數(shù)。

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')
})

在一個掛載點(diǎn)裝載一組中間件:

它將任何類型的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()
})

路由句柄的好處:

路徑處理程序使您可以為路徑定義多個路徑。下面的示例為/user/:id路徑的GET請求定義了兩個路由。第二個路由不會引起任何問題,但它永遠(yuǎn)不會被調(diào)用,因為第一個路由結(jié)束了請求 - 響應(yīng)周期。
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 ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id)
})

如果需要在中間件棧中跳過剩余中間件,調(diào)用 next(‘route’) 方法將控制權(quán)交給下一個路由。需要 注意的是:next('route')僅適用于使用app.METHOD()或router.METHOD()函數(shù)加載的中間件函數(shù)。

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) {
  // send a regular response
  res.send('regular')
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function (req, res, next) {
  res.send('special')
})

路由器級別中間件

路由器級中間件的工作方式與應(yīng)用程序級中間件的工作方式相同,但它綁定到的是一個實例express.Router()。

var router = express.Router()enter code here

使用router.use()和router.METHOD()函數(shù)加載路由器級中間件。
例子:

var app = express()
var router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.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 path
router.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 path
router.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 page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id)
  res.render('special')
})

// mount the router on the app
app.use('/', router)

調(diào)用next(“router”)跳過路由器中間件的其余功能,將控制權(quán)還給路由器實例
例子:

var app = express()
var router = express.Router()

// predicate the router with a check and bail out when needed
router.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 through
app.use('/admin', router, function (req, res) {
  res.sendStatus(401)
})

錯誤處理中間件

四個參數(shù):(err, req, res, next)
例子:

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

注意:即使你用不到next,也必須有這個簽名。

內(nèi)置中間件

  1. express.static提供靜態(tài)資源,如HTML文件,圖像等。
  2. express.json使用JSON有效負(fù)載解析傳入的請求。注意:適用于Express 4.16.0+
  3. express.urlencoded用URL編碼的有效負(fù)載解析傳入的請求。 注意:適用于Express 4.16.0+

第三方中間件

使用前需要先安裝相應(yīng)模塊,然后再中間件中加載
例子:這里用cookie解釋中間件作為例子
安裝模塊

$ npm install cookie-parser

引用

var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')

// load the cookie-parsing middleware
app.use(cookieParser())
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容