Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.Express是一个路由和中间件web框架,其自身的功能最少:Express应用程序本质上是一系列中间件函数调用。
Middleware functions are functions that have access to the request object (中间件函数是可以访问请求对象(req
), the response object (res
), and the next middleware function in the application’s request-response cycle. req
)、响应对象(res
)和应用程序请求-响应周期中的下一个中间件功能的功能。The next middleware function is commonly denoted by a variable named next中间件函数通常由名为next
.next
的变量表示。
Middleware functions can perform the following tasks:中间件功能可以执行以下任务:
If the current middleware function does not end the request-response cycle, it must call 如果当前中间件函数没有结束请求-响应周期,它必须调用next()
to pass control to the next middleware function. next()
将控制权传递给下一个中间件函数。Otherwise, the request will be left hanging.否则,请求将挂起。
An Express application can use the following types of middleware:Express应用程序可以使用以下类型的中间件:
You can load application-level and router-level middleware with an optional mount path. 您可以使用可选的装载路径加载应用程序级和路由器级中间件。You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.您还可以同时加载一系列中间件功能,这将在装入点创建中间件系统的子堆栈。
Bind application-level middleware to an instance of the app object by using the 使用app.use()
and app.METHOD()
functions, where METHOD
is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.app.use()
和app.METHOD()
函数将应用程序级中间件绑定到app对象的实例,其中METHOD是中间件函数以小写形式处理的请求(如GET、PUT或POST)的HTTP方法。
This example shows a middleware function with no mount path. 此示例显示了一个没有装载路径的中间件函数。The function is executed every time the app receives a request.每次应用程序收到请求时都会执行该功能。
var express = require('express')
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
This example shows a middleware function mounted on the 此示例显示了安装在/user/:id
path. /user/:id
路径上的中间件函数。The function is executed for any type of HTTP request on the 该函数针对/user/:id
path./user/:id
路径上的任何类型的HTTP请求执行。
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
This example shows a route and its handler function (middleware system). 此示例显示了一个路由及其处理程序功能(中间件系统)。The function handles GET requests to the 该函数处理对/user/:id
path./user/:id
路径的GET请求。
app.get('/user/:id', function (req, res, next) {
res.send('USER')
})
Here is an example of loading a series of middleware functions at a mount point, with a mount path. 下面是一个在装载点加载一系列中间件函数的示例,其中包含装载路径。It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the 它演示了一个中间件子堆栈,它将任何类型的HTTP请求的请求信息打印到/user/:id
path./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()
})
Route handlers enable you to define multiple routes for a path. 路由处理程序允许您为路径定义多个路由。The example below defines two routes for GET requests to the 下面的示例为/user/:id
path. /user/:id
路径的GET请求定义了两条路由。The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.第二条路由不会引起任何问题,但它永远不会被调用,因为第一条路由结束了请求-响应周期。
This example shows a middleware sub-stack that handles GET requests to the 此示例显示了一个中间件子堆栈,用于处理对/user/:id
path./user/:id
路径的GET请求。
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)
})
To skip the rest of the middleware functions from a router middleware stack, call 要从路由器中间件堆栈中跳过其余的中间件功能,请调用next('route')
to pass control to the next route. next('route')
将控制权传递给下一个路由。NOTE: 注意:next('route')
will work only in middleware functions that were loaded by using the app.METHOD()
or router.METHOD()
functions.next('route')
将仅在使用app.METHOD()
或router.METHOD()
函数加载的中间件函数中工作。
This example shows a middleware sub-stack that handles GET requests to the 此示例显示了一个中间件子堆栈,用于处理对/user/:id
path./user/:id
路径的GET请求。
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')
// 否则,将控制传递给该堆栈中的下一个中间件函数
else next()
}, function (req, res, next) {
// send a regular response
res.send('regular')
})
// /user/:id路径的处理程序,该路径发送特殊响应
app.get('/user/:id', function (req, res, next) {
res.send('special')
})
Middleware can also be declared in an array for reusability.中间件也可以在数组中声明以实现重用。
This example shows an array with a middleware sub-stack that handles GET requests to the 此示例显示了一个具有中间件子堆栈的阵列,该子堆栈处理对/user/:id
path/user/:id
路径的GET请求
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')
})
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of 路由器级中间件的工作方式与应用程序级中间件相同,只是它绑定到express.Router()
.express.Router()
的实例。
var router = express.Router()
Load router-level middleware by using the 使用router.use()
and router.METHOD()
functions.router.use()
和router.METHOD()
函数加载路由器级中间件。
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:下面的示例代码通过使用路由器级中间件复制了上面显示的应用程序级中间件的中间件系统:
var express = require('express')
var app = express()
var router = express.Router()
// 没有装载路径的中间件函数。对路由器的每个请求都执行此代码
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// 中间件子堆栈向/user/:id路径显示任何类型的HTTP请求的请求信息
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()
})
// 中间件子堆栈,用于处理对/user/:id路径的GET请求
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')
// 否则,将控制传递给该堆栈中的下一个中间件函数
else next()
}, function (req, res, next) {
// render a regular page
res.render('regular')
})
// /user/:id路径的处理程序,用于呈现特殊页面
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id)
res.render('special')
})
// 在应用程序上安装路由器
app.use('/', router)
To skip the rest of the router’s middleware functions, call 要跳过路由器的其余中间件功能,请调用next('router')
to pass control back out of the router instance.next('router')
将控制权传递回路由器实例。
This example shows a middleware sub-stack that handles GET requests to the 此示例显示了一个中间件子堆栈,用于处理对/user/:id
path./user/:id
路径的GET请求。
var express = require('express')
var app = express()
var router = express.Router()
// 在需要时,通过检查和跳出断言路由器
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!')
})
// 使用路由器和任何掉下的东西
app.use('/admin', router, function (req, res) {
res.sendStatus(401)
})
Error-handling middleware always takes four arguments. 错误处理中间件始终具有四个参数。You must provide four arguments to identify it as an error-handling middleware function. 必须提供四个参数才能将其标识为错误处理中间件函数。Even if you don’t need to use the 即使不需要使用next
object, you must specify it to maintain the signature. next
对象,也必须指定它来维护签名。Otherwise, the 否则,next
object will be interpreted as regular middleware and will fail to handle errors.next
对象将被解释为常规中间件,无法处理错误。
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature 以与其他中间件函数相同的方式定义错误处理中间件函数,除了使用四个参数而不是三个参数,特别是使用签名(err, req, res, next)
):(err, req, res, next)
):
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
For details about error-handling middleware, see: Error handling.有关错误处理中间件的详细信息,请参阅:错误处理。
Starting with version 4.x, Express no longer depends on Connect. 从4.x版开始,Express不再依赖于Connect。The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions.以前包含在Express中的中间件功能现在位于单独的模块中;请参见中间件功能列表。
Express has the following built-in middleware functions:Express具有以下内置中间件功能:
Use third-party middleware to add functionality to Express apps.使用第三方中间件为Express应用程序添加功能。
Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.为所需功能安装Node.js模块,然后在应用程序级别或路由器级别将其加载到应用程序中。
The following example illustrates installing and loading the cookie-parsing middleware function 以下示例说明如何安装和加载cookie解析中间件函数cookie-parser
.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())
For a partial list of third-party middleware functions that are commonly used with Express, see: Third-party middleware.有关Express常用的第三方中间件功能的部分列表,请参阅:第三方中间件。