使用中间件

发布时间 2023-09-05 18:35:52作者: linux星

使用中间件

Express 是一个路由和中间件 Web 框架,它自己的功能很少:Express 应用程序本质上是一系列中间件函数调用。

中间件函数是有权访问请求对象 ()、响应对象 () 和应用程序请求-响应周期中的下一个中间件函数的函数。下一个中间件函数通常由名为 的变量表示。reqresnext

中间件函数可以执行以下任务:

  • 执行任何代码。
  • 对请求和响应对象进行更改。
  • 结束请求-响应周期。
  • 调用堆栈中的下一个中间件函数。

如果当前中间件函数没有结束请求-响应周期,则必须调用以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。next()

快速应用程序可以使用以下类型的中间件:

您可以使用可选的挂载路径加载应用程序级和路由器级中间件。 您还可以一起加载一系列中间件函数,从而在挂载点创建中间件系统的子堆栈。

应用级中间件

使用 and 函数将应用程序级中间件绑定到应用程序对象的实例,其中中间件函数以小写形式处理的请求(例如 GET、PUT 或 POST)的 HTTP 方法。app.use()app.METHOD()METHOD

此示例显示了一个没有挂载路径的中间件函数。每次应用收到请求时都会执行该函数。

var express = require('express')
var app = express()

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

此示例显示了挂载在路径上的中间件函数。该函数适用于任何类型的 路径上的 HTTP 请求。/user/:id/user/:id

app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

此示例显示路由及其处理程序函数(中间件系统)。该函数处理对路径的 GET 请求。/user/:id

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 ID
app.get('/user/:id', function (req, res, next) {
  res.send(req.params.id)
})

要跳过路由器中间件堆栈中的其余中间件功能,请调用以将控制权传递给下一个路由。注意:仅适用于使用 or 函数加载的中间件函数。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) {
  // 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')
})

中间件也可以在数组中声明以实现可重用性。

此示例显示了一个具有中间件子堆栈的数组,该子堆栈处理对路径的 GET 请求/user/:id

function logOriginalUrl (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}

function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}

var logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, function (req, res, next) {
  res.send('User Info')
})

路由器级中间件

路由器级中间件的工作方式与应用程序级中间件相同,只是它绑定到 的实例。express.Router()

var router = express.Router()

使用 and 函数加载路由器级中间件。router.use()router.METHOD()

以下示例代码使用路由器级中间件复制上面显示的应用程序级中间件的中间件系统:

var express = require('express')
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)

要跳过路由器的其余中间件功能,请调用以将控制权传回路由器实例。next('router')

此示例显示了一个中间件子堆栈,用于处理对路径的 GET 请求。/user/:id

var express = require('express')
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('/user/:id', 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)
})

错误处理中间件

错误处理中间件始终采用四个参数。您必须提供四个参数才能将其标识为错误处理中间件函数。即使不需要使用该对象,也必须指定它以维护签名。否则,该对象将被解释为常规中间件,并且无法处理错误。nextnext

定义错误处理中间件函数的方式与其他中间件函数相同,除了使用四个参数而不是三个参数,特别是使用签名):(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 中的功能现在位于单独的模块中;请参阅中间件函数列表

Express 具有以下内置中间件功能:

  • express.static 提供静态资产,如 HTML 文件、图像等。
  • express.json 使用 JSON 有效负载解析传入请求。注意:适用于快速版 4.16.0+
  • express.urlencoded 使用 URL 编码的有效负载解析传入请求。注意:适用于快速版 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 middleware
app.use(cookieParser())

有关通常与 Express 一起使用的第三方中间件函数的部分列表,请参阅:第三方中间件