5.x API

注意: 这是早期的 beta 文档,可能不完整并且仍在开发中。

express()

创建一个 Express 应用。express() 函数是 express 模块导出的顶层函数。

Creates an Express application. The express() function is a top-level function exported by the express module.

const express = require('express')
const app = express()

方法

express.json([options])

这是 Express 中内置的中间件函数。它使用 JSON 有效负载解析传入请求,并且基于 body-parser

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

返回仅解析 JSON 并且仅查看 Content-Type 标头与 type 选项匹配的请求的中间件。此解析器接受正文的任何​​ Unicode 编码,并支持 gzipdeflate 编码的自动膨胀。

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

包含解析数据的新 body 对象在中间件(即 req.body)之后填充到 request 对象上,如果没有要解析的主体、Content-Type 不匹配或发生错误,则填充一个空对象({})。

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

由于 req.body 的形状基于用户控制的输入,因此该对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能以多种方式失败,例如 foo 可能不存在或可能不是字符串,并且 toString 可能不是函数而是字符串或其他用户输入。

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

下表描述了可选 options 对象的属性。

The following table describes the properties of the optional options object.

属性 描述 类型 默认
inflate 启用或禁用处理放气(压缩)的对象;当禁用时,泄气的主体会被拒绝。 布尔值 true
limit 控制最大请求正文大小。如果这是一个数字,则该值指定字节数;如果是字符串,则将该值传递给 bytes 库进行解析。 混合 "100kb"
reviver reviver 选项作为第二个参数直接传递给 JSON.parse。你可以找到有关此参数 在关于 JSON.parse 的 MDN 文档中 的更多信息。 函数 null
strict 启用或禁用仅接受数组和对象;禁用时将接受 JSON.parse 接受的任何内容。 布尔值 true
type 这用于确定中间件将解析的媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项直接传递给 type-is 库,它可以是扩展名(如 json)、mime 类型(如 application/json)或带有通配符的 mime 类型(如 */**/json)。如果是函数,则 type 选项被称为 fn(req),如果请求返回真值,则解析请求。 混合 "application/json"
verify 此选项(如果提供)称为 verify(req, res, buf, encoding),其中 buf 是原始请求正文的 Bufferencoding 是请求的编码。可以通过抛出错误来中止解析。 函数 undefined

express.static(root, [options])

这是 Express 中内置的中间件函数。它提供静态文件并且基于 serve-static

This is a built-in middleware function in Express. It serves static files and is based on serve-static.

注意:为了获得最佳结果,使用反向代理 缓存可提高静态资源服务的性能。

NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.

root 参数指定提供静态资源的根目录。该函数通过将 req.url 与提供的 root 目录组合来确定要服务的文件。当找不到文件时,它不会发送 404 响应,而是调用 next() 以继续下一个中间件,从而允许堆叠和回退。

The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it instead calls next() to move on to the next middleware, allowing for stacking and fall-backs.

下表描述了 options 对象的属性。另见 下面的例子

The following table describes the properties of the options object. See also the example below.

属性 描述 类型 默认
dotfiles 确定如何处理点文件(以点 “.” 开头的文件或目录)。请参见下面的 dotfiles 字符串 “ignore”
etag 启用或禁用 etag 生成。注意:express.static 总是发送弱 ETag。 布尔值 true
extensions 设置文件扩展名后备:如果找不到文件,请搜索具有指定扩展名的文件并提供第一个找到的文件。示例:['html', 'htm'] 混合 false
fallthrough 让客户端错误作为未处理的请求通过,否则转发客户端错误。请参见下面的 fallthrough 布尔值 true
immutable Cache-Control 响应标头中启用或禁用 immutable 指令。如果启用,还应指定 maxAge 选项以启用缓存。immutable 指令将阻止受支持的客户端在 maxAge 选项的生命周期内发出条件请求以检查文件是否已更改。 布尔值 false
index 发送指定的目录索引文件。设置为 false 以禁用目录索引。 混合 “index.html”
lastModified Last-Modified 标头设置为操作系统上文件的最后修改日期。 布尔值 true
maxAge 设置 Cache-Control 标头的 max-age 属性(以毫秒为单位)或 ms 格式 中的字符串。 数字 0
redirect 当路径名是目录时,重定向到尾随 “/”。 布尔值 true
setHeaders 用于设置 HTTP 标头以与文件一起服务的功能。请参见下面的 setHeaders 函数  

有关详细信息,请参阅 在 Express 中提供静态文件。和 使用中间件 - 内置中间件

For more information, see Serving static files in Express. and Using middleware - Built-in middleware.

dotfiles

此选项的可能值为:

Possible values for this option are:

  • “allow” - 对点文件没有特殊处理。

    “allow” - No special treatment for dotfiles.

  • “deny” - 拒绝点文件请求,以 403 响应,然后调用 next()

    “deny” - Deny a request for a dotfile, respond with 403, then call next().

  • “ignore” - 就好像 dotfile 不存在一样,用 404 响应,然后调用 next()

    “ignore” - Act as if the dotfile does not exist, respond with 404, then call next().

fallthrough

当此选项为 true 时,客户端错误(例如错误请求或对不存在文件的请求)将导致此中间件简单地调用 next() 以调用堆栈中的下一个中间件。当为 false 时,这些错误(甚至是 404)将调用 next(err)

When this option is true, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call next() to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke next(err).

将此选项设置为 true,以便你可以将多个物理目录映射到同一个 Web 地址或路由以填充不存在的文件。

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

如果你已将此中间件安装在严格设计为单个文件系统目录的路径上,请使用 false,这允许短路 404 以减少开销。这个中间件也会响应所有的方法。

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

setHeaders

对于此选项,指定一个函数来设置自定义响应标头。对标头的更改必须同步发生。

For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.

该函数的签名是:

The signature of the function is:

fn(res, path, stat)

参数:

Arguments:

  • res响应对象

    res, the response object.

  • path,正在发送的文件路径。

    path, the file path that is being sent.

  • stat,正在发送的文件的 stat 对象。

    stat, the stat object of the file that is being sent.

Express.static 的示例

下面是一个将 express.static 中间件函数与精心设计的选项对象一起使用的示例:

Here is an example of using the express.static middleware function with an elaborate options object:

const options = {
  dotfiles: 'ignore',
  etag: false,
  extensions: ['htm', 'html'],
  index: false,
  maxAge: '1d',
  redirect: false,
  setHeaders (res, path, stat) {
    res.set('x-timestamp', Date.now())
  }
}

app.use(express.static('public', options))

express.Router([options])

创建一个新的 router 对象。

Creates a new router object.

const router = express.Router([options])

可选的 options 参数指定路由的行为。

The optional options parameter specifies the behavior of the router.

属性 描述 默认 可用性
caseSensitive 启用区分大小写。 默认禁用,将 “/Foo” 和 “/foo” 视为相同。  
mergeParams 保留来自父路由的 req.params 值。如果父项和子项的参数名称冲突,则子项的值优先。 false 4.5.0+
strict 启用严格路由。 默认情况下禁用,路由对 “/foo” 和 “/foo/” 的处理相同。  

你可以像应用一样将中间件和 HTTP 方法路由(例如 getputpost 等)添加到 router

You can add middleware and HTTP method routes (such as get, put, post, and so on) to router just like an application.

有关详细信息,请参阅 路由

For more information, see Router.

express.urlencoded([options])

这是 Express 中内置的中间件函数。它使用 urlencoded 有效负载解析传入的请求,并且基于 body-parser

This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

返回仅解析 urlencoded 正文并仅查看 Content-Type 标头与 type 选项匹配的请求的中间件。此解析器仅接受正文的 UTF-8 编码,并支持 gzipdeflate 编码的自动膨胀。

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

包含解析数据的新 body 对象在中间件(即 req.body)之后填充到 request 对象上,如果没有要解析的主体、Content-Type 不匹配或发生错误,则填充一个空对象({})。该对象将包含键值对,其中值可以是字符串或数组(当 extendedfalse 时)或任何类型(当 extendedtrue 时)。

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

由于 req.body 的形状基于用户控制的输入,因此该对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能以多种方式失败,例如 foo 可能不存在或可能不是字符串,并且 toString 可能不是函数而是字符串或其他用户输入。

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

下表描述了可选 options 对象的属性。

The following table describes the properties of the optional options object.

属性 描述 类型 默认
extended 此选项允许在使用 querystring 库(当 false)或 qs 库(当 true)解析 URL 编码数据之间进行选择。”extended” 语法允许将丰富的对象和数组编码为 URL 编码格式,从而提供类似 JSON 的 URL 编码体验。欲了解更多信息,请 查看 qs 库 布尔值 false
inflate 启用或禁用处理放气(压缩)的对象;当禁用时,泄气的主体会被拒绝。 布尔值 true
limit 控制最大请求正文大小。如果这是一个数字,则该值指定字节数;如果是字符串,则将该值传递给 bytes 库进行解析。 混合 "100kb"
parameterLimit 此选项控制 URL 编码数据中允许的最大参数数。如果请求包含的参数多于该值,则会引发错误。 数字 1000
type 这用于确定中间件将解析的媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项直接传递给 type-is 库,它可以是扩展名(如 urlencoded)、mime 类型(如 application/x-www-form-urlencoded)或带有通配符的 mime 类型(如 */x-www-form-urlencoded)。如果是函数,则 type 选项被称为 fn(req),如果请求返回真值,则解析请求。 混合 "application/x-www-form-urlencoded"
verify 此选项(如果提供)称为 verify(req, res, buf, encoding),其中 buf 是原始请求正文的 Bufferencoding 是请求的编码。可以通过抛出错误来中止解析。 函数 undefined

应用

app 对象通常表示 Express 应用。通过调用 Express 模块导出的顶层 express() 函数来创建它:

The app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('hello world')
})

app.listen(3000)

app 对象具有用于

The app object has methods for

它还具有影响应用行为方式的设置(属性);有关详细信息,请参阅 应用设置

It also has settings (properties) that affect how the application behaves; for more information, see Application settings.

Express 应用对象可以从 请求对象响应对象 分别被称为 req.appres.app

The Express application object can be referred from the request object and the response object as req.app, and res.app, respectively.

属性

app.locals

app.locals 对象的属性是应用中的局部变量,并且可以在使用 res.render 渲染的模板中使用。

The app.locals object has properties that are local variables within the application, and will be available in templates rendered with res.render.

console.dir(app.locals.title)
// => 'My App'

console.dir(app.locals.email)
// => 'me@myapp.com'

设置后,app.locals 属性的值将在应用的整个生命周期中保持不变,而 res.locals 属性仅在请求的生命周期内有效。

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

你可以访问应用中渲染的模板中的局部变量。这对于为模板以及应用级数据提供帮助函数很有用。局部变量可通过 req.app.locals 在中间件中使用(参见 req.app

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = 'me@myapp.com'

app.mountpath

app.mountpath 属性包含一个或多个安装子应用的路径模式。

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

子应用是 express 的一个实例,可用于处理对路由的请求。

A sub-app is an instance of express that may be used for handling the request to a route.

const express = require('express')

const app = express() // the main app
const admin = express() // the sub app

admin.get('/', (req, res) => {
  console.log(admin.mountpath) // /admin
  res.send('Admin Homepage')
})

app.use('/admin', admin) // mount the sub app

它类似于 req 对象的 baseUrl 属性,除了 req.baseUrl 返回匹配的 URL 路径,而不是匹配的模式。

It is similar to the baseUrl property of the req object, except req.baseUrl returns the matched URL path, instead of the matched patterns.

如果子应用挂载在多个路径模式上,app.mountpath 返回其挂载的模式列表,如下例所示。

If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on, as shown in the following example.

const admin = express()

admin.get('/', (req, res) => {
  console.log(admin.mountpath) // [ '/adm*n', '/manager' ]
  res.send('Admin Homepage')
})

const secret = express()
secret.get('/', (req, res) => {
  console.log(secret.mountpath) // /secr*t
  res.send('Admin Secret')
})

admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app

app.router

应用的内置路由实例。这是在第一次访问时懒惰地创建的。

The application’s in-built instance of router. This is created lazily, on first access.

const express = require('express')
const app = express()
const router = app.router

router.get('/', (req, res) => {
  res.send('hello world')
})

app.listen(3000)

你可以像应用一样向 router 添加中间件和 HTTP 方法路由。

You can add middleware and HTTP method routes to the router just like an application.

有关详细信息,请参阅 路由

For more information, see Router.

事件

app.on('mount', callback(parent))

当子应用安装在父应用上时,mount 事件会在子应用上触发。父应用被传递给回调函数。

The mount event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.

注意

NOTE

子应用将:

Sub-apps will:

  • 不继承具有默认值的设置值。你必须在子应用中设置该值。

    Not inherit the value of settings that have a default value. You must set the value in the sub-app.

  • 继承设置的值,没有默认值。

    Inherit the value of settings with no default value.

详见 应用设置

For details, see Application settings.

const admin = express()

admin.on('mount', (parent) => {
  console.log('Admin Mounted')
  console.log(parent) // refers to the parent app
})

admin.get('/', (req, res) => {
  res.send('Admin Homepage')
})

app.use('/admin', admin)

方法

app.all(path, callback [, callback ...])

此方法类似于标准 app.METHOD() 方法,不同之处在于它匹配所有 HTTP 动词。

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

示例

Examples

无论使用 GET、POST、PUT、DELETE 还是任何其他 HTTP 请求方法,对 /secret 的请求都会执行以下回调:

The following callback is executed for requests to /secret whether using GET, POST, PUT, DELETE, or any other HTTP request method:

app.all('/secret', (req, res, next) => {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

app.all() 方法对于为特定路径前缀或任意匹配映射 “global” 逻辑很有用。例如,如果你将以下内容放在所有其他路由定义的顶部,则要求从该点开始的所有路由都需要身份验证,并自动加载用户。请记住,这些回调不必充当端点:loadUser 可以执行一个任务,然后调用 next() 继续匹配后续路由。

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: loadUser can perform a task, then call next() to continue matching subsequent routes.

app.all('*', requireAuthentication, loadUser)

或等价物:

Or the equivalent:

app.all('*', requireAuthentication)
app.all('*', loadUser)

另一个示例是列入白名单的 “global” 功能。该示例与上面的示例类似,但它仅限制以 “/api” 开头的路径:

Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:

app.all('/api/*', requireAuthentication)

app.delete(path, callback [, callback ...])

使用指定的回调函数将 HTTP DELETE 请求路由到指定路径。有关详细信息,请参阅 路由指南

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

示例

Example

app.delete('/', (req, res) => {
  res.send('DELETE request to homepage')
})

app.disable(name)

将布尔设置 name 设置为 false,其中 name应用设置表 的属性之一。为布尔属性调用 app.set('foo', false) 与调用 app.disable('foo') 相同。

Sets the Boolean setting name to false, where name is one of the properties from the app settings table. Calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').

例如:

For example:

app.disable('trust proxy')
app.get('trust proxy')
// => false

app.disabled(name)

如果禁用布尔设置 name (false),则返回 true,其中 name应用设置表 的属性之一。

Returns true if the Boolean setting name is disabled (false), where name is one of the properties from the app settings table.

app.disabled('trust proxy')
// => true

app.enable('trust proxy')
app.disabled('trust proxy')
// => false

app.enable(name)

将布尔设置 name 设置为 true,其中 name应用设置表 的属性之一。为布尔属性调用 app.set('foo', true) 与调用 app.enable('foo') 相同。

Sets the Boolean setting name to true, where name is one of the properties from the app settings table. Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo').

app.enable('trust proxy')
app.get('trust proxy')
// => true

app.enabled(name)

如果启用了设置 name (true),则返回 true,其中 name应用设置表 的属性之一。

Returns true if the setting name is enabled (true), where name is one of the properties from the app settings table.

app.enabled('trust proxy')
// => false

app.enable('trust proxy')
app.enabled('trust proxy')
// => true

app.engine(ext, callback)

将给定的模板引擎 callback 注册为 ext

Registers the given template engine callback as ext.

默认情况下,Express 会根据文件扩展名 require() 引擎。例如,如果你尝试渲染 “foo.pug” 文件,Express 会在内部调用以下内容,并在后续调用时缓存 require() 以提高性能。

By default, Express will require() the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.

app.engine('pug', require('pug').__express)

对于不提供开箱即用的 .__express 的引擎,或者如果你希望 “map” 为模板引擎提供不同的扩展,请使用此方法。

Use this method for engines that do not provide .__express out of the box, or if you wish to “map” a different extension to the template engine.

例如,要将 EJS 模板引擎映射到 “.html” 文件:

For example, to map the EJS template engine to “.html” files:

app.engine('html', require('ejs').renderFile)

在这种情况下,EJS 提供了一个 .renderFile() 方法,其签名与 Express 所期望的相同:(path, options, callback),但请注意,它在内部将此方法别名为 ejs.__express,因此如果你使用 “.ejs” 扩展,则无需执行任何操作。

In this case, EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally so if you’re using “.ejs” extensions you don’t need to do anything.

一些模板引擎不遵循这个约定。consolidate.js 库映射 Node 模板引擎以遵循此约定,因此它们可以与 Express 无缝协作。

Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

const engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)

app.get(name)

返回 name 应用设置的值,其中 name应用设置表 中的字符串之一。例如:

Returns the value of name app setting, where name is one of the strings in the app settings table. For example:

app.get('title')
// => undefined

app.set('title', 'My Site')
app.get('title')
// => "My Site"

app.get(path, callback [, callback ...])

使用指定的回调函数将 HTTP GET 请求路由到指定路径。

Routes HTTP GET requests to the specified path with the specified callback functions.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

有关详细信息,请参阅 路由指南

For more information, see the routing guide.

示例

Example

app.get('/', (req, res) => {
  res.send('GET request to homepage')
})

app.listen(path, [callback])

启动一个 UNIX 套接字并监听给定路径上的连接。此方法与 Node 的 http.Server.listen() 相同。

Starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s http.Server.listen().

const express = require('express')
const app = express()
app.listen('/tmp/sock')

app.listen([port[, host[, backlog]]][, callback])

绑定并监听指定主机和端口上的连接。此方法与 Node 的 http.Server.listen() 相同。

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().

如果端口被省略或为 0,操作系统将分配一个任意未使用的端口,这对于自动化任务(测试等)等情况很有用。

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

const express = require('express')
const app = express()
app.listen(3000)

express() 返回的 app 实际上是一个 JavaScript Function,旨在作为回调传递给 Node 的 HTTP 服务器来处理请求。这使得为​​你的应用的 HTTP 和 HTTPS 版本提供相同的代码库变得很容易,因为应用不会从这些版本继承(它只是一个回调):

The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

const express = require('express')
const https = require('https')
const http = require('http')
const app = express()

http.createServer(app).listen(80)
https.createServer(options, app).listen(443)

app.listen() 方法返回一个 http.Server 对象,并且(对于 HTTP)是以下的便捷方法:

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function () {
  const server = http.createServer(this)
  return server.listen.apply(server, arguments)
}

注意:Node 的 http.Server.listen() 方法的所有形式实际上都受到支持。

NOTE: All the forms of Node’s http.Server.listen() method are in fact actually supported.

app.METHOD(path, callback [, callback ...])

路由 HTTP 请求,其中 METHOD 是请求的 HTTP 方法,如 GET、PUT、POST 等,小写。因此,实际的方法是 app.get()app.post()app.put() 等等。有关完整列表,请参见下面的 路由方法

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on. See Routing methods below for the complete list.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

路由方法

Routing methods

Express 支持以下与 HTTP 同名方法对应的路由方法:

Express supports the following routing methods corresponding to the HTTP methods of the same names:

  • checkout

  • copy

  • delete

  • get

  • head

  • lock

  • merge

  • mkactivity

  • mkcol

  • move

  • m-search

  • notify

  • options

  • patch

  • post

  • purge

  • put

  • report

  • search

  • subscribe

  • trace

  • unlock

  • unsubscribe

API 文档仅针对最流行的 HTTP 方法 app.get()app.post()app.put()app.delete() 有明确的条目。但是,上面列出的其他方法的工作方式完全相同。

The API documentation has explicit entries only for the most popular HTTP methods app.get(), app.post(), app.put(), and app.delete(). However, the other methods listed above work in exactly the same way.

要路由转换为无效 JavaScript 变量名的方法,请使用方括号表示法。例如,app['m-search']('/', function ...

To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ....

如果在 app.get() 之前没有为路径调用 app.head(),除了 GET 方法之外,还会自动为 HTTP HEAD 方法调用 app.get() 函数。

The app.get() function is automatically called for the HTTP HEAD method in addition to the GET method if app.head() was not called for the path before app.get().

方法 app.all() 不是从任何 HTTP 方法派生的,而是在指定路径为所有 HTTP 请求方法加载中间件。有关详细信息,请参阅 app.all

The method, app.all(), is not derived from any HTTP method and loads middleware at the specified path for all HTTP request methods. For more information, see app.all.

有关路由的更多信息,请参阅 路由指南

For more information on routing, see the routing guide.

app.param(name, callback)

路由参数 中添加回调触发器,其中 name 是参数名称或参数数组,callback 是回调函数。回调函数的参数依次是请求对象、响应对象、下一个中间件、参数的值和参数的名称。

Add callback triggers to route parameters, where name is the name of the parameter or an array of them, and callback is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

如果 name 是一个数组,则为其中声明的每个参数注册 callback 触发器,按照它们的声明顺序。此外,对于除最后一个之外的每个声明的参数,在回调中调用 next 将为下一个声明的参数调用回调。对于最后一个参数,对 next 的调用将调用当前正在处理的路由的下一个中间件,就像 name 只是一个字符串一样。

If name is an array, the callback trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to next inside the callback will call the callback for the next declared parameter. For the last parameter, a call to next will call the next middleware in place for the route currently being processed, just like it would if name were just a string.

例如,当 :user 出现在路由路径中时,你可以映射用户加载逻辑以自动将 req.user 提供给路由,或对参数输入执行验证。

For example, when :user is present in a route path, you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

app.param('user', (req, res, next, id) => {
  // try to get the user details from the User model and attach it to the request object
  User.find(id, (err, user) => {
    if (err) {
      next(err)
    } else if (user) {
      req.user = user
      next()
    } else {
      next(new Error('failed to load user'))
    }
  })
})

参数回调函数在定义它们的路由上是本地的。它们不会被安装的应用或路由继承。因此,在 app 上定义的参数回调将仅由在 app 路由上定义的路由参数触发。

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on app will be triggered only by route parameters defined on app routes.

所有参数回调将在参数出现的任何路由的任何处理程序之前调用,并且它们在请求-响应周期中仅被调用一次,即使参数在多个路由中匹配,如下例所示。

All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

app.param('id', (req, res, next, id) => {
  console.log('CALLED ONLY ONCE')
  next()
})

app.get('/user/:id', (req, res, next) => {
  console.log('although this matches')
  next()
})

app.get('/user/:id', (req, res) => {
  console.log('and this matches too')
  res.end()
})

GET /user/42 上,打印以下内容:

On GET /user/42, the following is printed:

CALLED ONLY ONCE
although this matches
and this matches too
app.param(['id', 'page'], (req, res, next, value) => {
  console.log('CALLED ONLY ONCE with', value)
  next()
})

app.get('/user/:id/:page', (req, res, next) => {
  console.log('although this matches')
  next()
})

app.get('/user/:id/:page', (req, res) => {
  console.log('and this matches too')
  res.end()
})

GET /user/42/3 上,打印以下内容:

On GET /user/42/3, the following is printed:

CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too

app.path()

返回应用的规范路径,一个字符串。

Returns the canonical path of the app, a string.

const app = express()
const blog = express()
const blogAdmin = express()

app.use('/blog', blog)
blog.use('/admin', blogAdmin)

console.log(app.path()) // ''
console.log(blog.path()) // '/blog'
console.log(blogAdmin.path()) // '/blog/admin'

在安装应用的复杂情况下,此方法的行为可能会变得非常复杂:通常最好使用 req.baseUrl 来获取应用的规范路径。

The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use req.baseUrl to get the canonical path of the app.

app.post(path, callback [, callback ...])

使用指定的回调函数将 HTTP POST 请求路由到指定路径。有关详细信息,请参阅 路由指南

Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

示例

Example

app.post('/', (req, res) => {
  res.send('POST request to homepage')
})

app.put(path, callback [, callback ...])

使用指定的回调函数将 HTTP PUT 请求路由到指定路径。

Routes HTTP PUT requests to the specified path with the specified callback functions.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

示例

Example

app.put('/', (req, res) => {
  res.send('PUT request to homepage')
})

app.render(view, [locals], callback)

通过 callback 函数返回视图的渲染 HTML。它接受一个可选参数,该参数是一个包含视图局部变量的对象。它和 res.render() 一样,只是它不能自己将渲染视图发送给客户端。

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.

app.render() 视为生成渲染视图字符串的实用函数。在内部,res.render() 使用 app.render() 来渲染视图。

Think of app.render() as a utility function for generating rendered view strings. Internally res.render() uses app.render() to render views.

局部变量 cache 保留用于启用视图缓存。如果想在开发过程中缓存视图,则设置为 true;默认情况下,在生产环境中启用视图缓存。

The local variable cache is reserved for enabling view cache. Set it to true, if you want to cache view during development; view caching is enabled in production by default.

app.render('email', (err, html) => {
  // ...
})

app.render('email', { name: 'Tobi' }, (err, html) => {
  // ...
})

app.route(path)

返回单个路由的实例,然后你可以使用它来处理带有可选中间件的 HTTP 动词。使用 app.route() 来避免重复的路由名称(从而避免拼写错误)。

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

const app = express()

app.route('/events')
  .all((req, res, next) => {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
  })
  .get((req, res, next) => {
    res.json({})
  })
  .post((req, res, next) => {
    // maybe add a new event...
  })

app.set(name, value)

将设置 name 分配给 value。你可以存储任何你想要的值,但某些名称可用于配置服务器的行为。这些特殊名称列在 应用设置表 中。

Assigns setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.

为布尔属性调用 app.set('foo', true) 与调用 app.enable('foo') 相同。同样,为布尔属性调用 app.set('foo', false) 与调用 app.disable('foo') 相同。

Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').

使用 app.get() 检索设置的值。

Retrieve the value of a setting with app.get().

app.set('title', 'My Site')
app.get('title') // "My Site"

应用设置

下表列出了应用设置。

The following table lists application settings.

请注意,子应用将:

Note that sub-apps will:

  • 不继承具有默认值的设置值。你必须在子应用中设置该值。

    Not inherit the value of settings that have a default value. You must set the value in the sub-app.

  • 继承没有默认值的设置值;下表明确指出了这些。

    Inherit the value of settings with no default value; these are explicitly noted in the table below.

例外:子应用将继承 trust proxy 的值,即使它具有默认值(为了向后兼容);子应用在生产环境中不会继承 view cache 的值(当 NODE_ENV 为 “production” 时)。

Exceptions: Sub-apps will inherit the value of trust proxy even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of view cache in production (when NODE_ENV is “production”).

PropertyTypeDescriptionDefault

case sensitive routing

Boolean

Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.

NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

env

String Environment mode. Be sure to set to "production" in a production environment; see Production best practices: performance and reliability.

process.env.NODE_ENVNODE_ENV 环境变量)或 “development”(如果未设置 NODE_ENV)。

process.env.NODE_ENV (NODE_ENV environment variable) or “development” if NODE_ENV is not set.

etag

Varied

设置 ETag 响应标头。有关可能的值,请参阅 etag 选项表

Set the ETag response header. For possible values, see the etag options table.

有关 HTTP ETag 标头的更多信息

More about the HTTP ETag header.

weak

jsonp callback name

String Specifies the default JSONP callback name.

“callback”

json escape

Boolean

启用来自 res.jsonres.jsonpres.send API 的转义 JSON 响应。这会将字符 <>& 转义为 JSON 中的 Unicode 转义序列。其目的是在客户端嗅探 HTML 响应时协助 减轻某些类型的持续 XSS 攻击

Enable escaping JSON responses from the res.json, res.jsonp, and res.send APIs. This will escape the characters <, >, and & as Unicode escape sequences in JSON. The purpose of this it to assist with mitigating certain types of persistent XSS attacks when clients sniff responses for HTML.

注意 NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

json replacer

Varied The 'replacer' argument used by `JSON.stringify`.

NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

json spaces

Varied The 'space' argument used by `JSON.stringify`. This is typically set to the number of spaces to use to indent prettified JSON.

NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

query parser

Varied

通过将值设置为 false 来禁用查询解析,或将查询解析器设置为使用 “simple” 或 “extended” 或自定义查询字符串解析函数。

Disable query parsing by setting the value to false, or set the query parser to use either “simple” or “extended” or a custom query string parsing function.

简单查询解析器基于 Node 的原生查询解析器 querystring

The simple query parser is based on Node’s native query parser, querystring.

扩展查询解析器基于 qs

The extended query parser is based on qs.

自定义查询字符串解析函数将接收完整的查询字符串,并且必须返回查询键及其值的对象。

A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.

"extended"

strict routing

Boolean

Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.

NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

subdomain offset

Number The number of dot-separated parts of the host to remove to access subdomain. 2

trust proxy

Varied

指示应用位于前置代理后面,并使用 X-Forwarded-* 标头来确定客户端的连接和 IP 地址。注意:X-Forwarded-* 标头很容易被欺骗,并且检测到的 IP 地址不可靠。

Indicates the app is behind a front-facing proxy, and to use the X-Forwarded-* headers to determine the connection and the IP address of the client. NOTE: X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.

When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table.

The `trust proxy` setting is implemented using the proxy-addr package. For more information, see its documentation.

NOTE: Sub-apps will inherit the value of this setting, even though it has a default value.

false(已禁用)

false (disabled)

views

String or Array A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.

process.cwd() + '/views'

view cache

Boolean

Enables view template compilation caching.

NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").

true 正在生产中,否则未定义。

true in production, otherwise undefined.

view engine

String The default engine extension to use when omitted.

NOTE: Sub-apps will inherit the value of this setting.

N/A (undefined)

x-powered-by

Boolean Enables the "X-Powered-By: Express" HTTP header.

true

`trust proxy` 设置选项

阅读 [Express Behind proxies]/en/behind-proxies.html) 了解更多信息。 Read [Express behind proxies]/en/behind-proxies.html) for more information.

TypeValue
Boolean

如果是 true,则客户端的 IP 地址被理解为 X-Forwarded-* 标头中最左侧的条目。

If true, the client’s IP address is understood as the left-most entry in the X-Forwarded-* header.

如果是 false,则应用理解为直接面向互联网,客户端的 IP 地址来源于 req.connection.remoteAddress。这是默认设置。

If false, the app is understood as directly facing the Internet and the client’s IP address is derived from req.connection.remoteAddress. This is the default setting.

String
String containing comma-separated values
Array of strings

IP 地址、子网或 IP 地址数组以及要信任的子网。预配置的子网名称为:

An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:

  • loopback - 127.0.0.1/8, ::1/128

  • linklocal - 169.254.0.0/16, fe80::/10

  • uniquelocal - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7

通过以下任一方式设置 IP 地址:

Set IP addresses in any of the following ways:

指定单个子网:

Specify a single subnet:

app.set('trust proxy', 'loopback')

指定子网和地址:

Specify a subnet and an address:

app.set('trust proxy', 'loopback, 123.123.123.123')

将多个子网指定为 CSV:

Specify multiple subnets as CSV:

app.set('trust proxy', 'loopback, linklocal, uniquelocal')

将多个子网指定为数组:

Specify multiple subnets as an array:

app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal'])

指定时,IP 地址或子网将被排除在地址确定过程之外,并将离应用服务器最近的不受信任的 IP 地址确定为客户端的 IP 地址。

When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address.

Number

信任来自前端代理服务器的nth跃点作为客户端。

Trust the nth hop from the front-facing proxy server as the client.

Function

自定义信任实现。仅当你知道自己在做什么时才使用此功能。

Custom trust implementation. Use this only if you know what you are doing.

app.set('trust proxy', (ip) => {
  if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs
  else return false
})
`etag` 设置选项

注意:这些设置仅适用于动态文件,不适用于静态文件。express.static 中间件会忽略这些设置。 NOTE: These settings apply only to dynamic files, not static files. The express.static middleware ignores these settings.

ETag 功能是使用 etag 包实现的。有关更多信息,请参阅其文档。 The ETag functionality is implemented using the etag package. For more information, see its documentation.

TypeValue
Boolean

true 启用弱 ETag。这是默认设置。false 完全禁用 ETag。

true enables weak ETag. This is the default setting.
false disables ETag altogether.

String If "strong", enables strong ETag.
If "weak", enables weak ETag.
Function

自定义 ETag 函数实现。仅当你知道自己在做什么时才使用此功能。

Custom ETag function implementation. Use this only if you know what you are doing.

app.set('etag', (body, encoding) => {
  return generateHash(body, encoding) // consider the function is defined
})

app.use([path,] callback [, callback...])

在指定路径挂载指定的 中间件 函数:当请求路径的基匹配 path 时执行中间件函数。

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

参数

Argument Description Default
path The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
例如,参见 路径示例For examples, see Path examples.
'/' (root path)
callback Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

描述

Description

路由将匹配紧随其路径且带有“/”的任何路径。例如:app.use('/apple', ...) 将匹配 “/apple”、”/apple/images”、”/apple/images/news” 等。

A route will match any path that follows its path immediately with a “/”. For example: app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.

由于 path 默认为 “/”,因此每次对应用的请求都会执行没有路径挂载的中间件。例如,这个中间件函数将针对应用的每个请求执行:

Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app.\ For example, this middleware function will be executed for every request to the app:

app.use((req, res, next) => {
  console.log('Time: %d', Date.now())
  next()
})

注意

NOTE

子应用将:

Sub-apps will:

  • 不继承具有默认值的设置值。你必须在子应用中设置该值。

    Not inherit the value of settings that have a default value. You must set the value in the sub-app.

  • 继承设置的值,没有默认值。

    Inherit the value of settings with no default value.

详见 应用设置

For details, see Application settings.

中间件函数是按顺序执行的,因此中间件包含的顺序很重要。

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

// this middleware will not allow the request to go beyond it
app.use((req, res, next) => {
  res.send('Hello World')
})

// requests will never reach this route
app.get('/', (req, res) => {
  res.send('Welcome')
})

错误处理中间件

Error-handling middleware

错误处理中间件总是需要四个参数。你必须提供四个参数以将其标识为错误处理中间件函数。即使你不需要使用 next 对象,你也必须指定它来维护签名。否则,next 对象将被解释为常规中间件,无法处理错误。有关错误处理中间件的详细信息,请参见:错误处理

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. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: Error handling.

以与其他中间件函数相同的方式定义错误处理中间件函数,除了使用四个参数而不是三个参数,特别是使用签名 (err, req, res, 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)):

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

路径示例

Path examples

下表提供了一些用于挂载中间件的有效 path 值的简单示例。

The following table provides some simple examples of valid path values for mounting middleware.

Type Example
Path

这将匹配以 /abcd 开头的路径:

This will match paths starting with /abcd:

app.use('/abcd', (req, res, next) => {
  next()
})
Path Pattern

这将匹配以 /abcd/abd 开头的路径:

This will match paths starting with /abcd and /abd:

app.use('/ab(c?)d', (req, res, next) => {
  next()
})
Regular Expression

这将匹配以 /abc/xyz 开头的路径:

This will match paths starting with /abc and /xyz:

app.use(/\/abc|\/xyz/, (req, res, next) => {
  next()
})
Array

这将匹配以 /abcd/xyza/lmn/pqr 开头的路径:

This will match paths starting with /abcd, /xyza, /lmn, and /pqr:

app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => {
  next()
})

中间件回调函数示例

Middleware callback function examples

下表提供了可用作 app.use()app.METHOD()app.all()callback 参数的中间件函数的一些简单示例。尽管这些示例适用于 app.use(),但它们也适用于 app.use()app.METHOD()app.all()

The following table provides some simple examples of middleware functions that can be used as the callback argument to app.use(), app.METHOD(), and app.all(). Even though the examples are for app.use(), they are also valid for app.use(), app.METHOD(), and app.all().

Usage Example
Single Middleware

你可以在本地定义并挂载中间件函数。

You can define and mount a middleware function locally.

app.use((req, res, next) => {
  next()
})

路由是有效的中间件。

A router is valid middleware.

const router = express.Router()
router.get('/', (req, res, next) => {
  next()
})
app.use(router)

Express 应用是有效的中间件。

An Express app is valid middleware.

const subApp = express()
subApp.get('/', (req, res, next) => {
  next()
})
app.use(subApp)
Series of Middleware

你可以在同一挂载路径上指定多个中间件函数。

You can specify more than one middleware function at the same mount path.

const r1 = express.Router()
r1.get('/', (req, res, next) => {
  next()
})

const r2 = express.Router()
r2.get('/', (req, res, next) => {
  next()
})

app.use(r1, r2)
Array

使用数组对中间件进行逻辑分组。

Use an array to group middleware logically.

const r1 = express.Router()
r1.get('/', (req, res, next) => {
  next()
})

const r2 = express.Router()
r2.get('/', (req, res, next) => {
  next()
})

app.use([r1, r2])
Combination

你可以将上述所有中间件的挂载方式组合起来。

You can combine all the above ways of mounting middleware.

function mw1 (req, res, next) { next() }
function mw2 (req, res, next) { next() }

const r1 = express.Router()
r1.get('/', (req, res, next) => { next() })

const r2 = express.Router()
r2.get('/', (req, res, next) => { next() })

const subApp = express()
subApp.get('/', (req, res, next) => { next() })

app.use(mw1, [mw2, r1, r2], subApp)

以下是在 Express 应用中使用 express.static 中间件的一些示例。

Following are some examples of using the express.static middleware in an Express app.

从应用目录中的 “public” 目录为应用提供静态内容:

Serve static content for the app from the “public” directory in the application directory:

// GET /style.css etc
app.use(express.static(path.join(__dirname, 'public')))

仅当请求路径以 “/static” 为前缀时,将中间件安装在 “/static” 以提供静态内容:

Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:

// GET /static/style.css etc.
app.use('/static', express.static(path.join(__dirname, 'public')))

通过在静态中间件之后加载日志器中间件来禁用静态内容请求的日志记录:

Disable logging for static content requests by loading the logger middleware after the static middleware:

app.use(express.static(path.join(__dirname, 'public')))
app.use(logger())

提供来自多个目录的静态文件,但 “./public” 优先于其他目录:

Serve static files from multiple directories, but give precedence to “./public” over the others:

app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))

请求

req 对象表示 HTTP 请求,并具有请求查询字符串、参数、正文、HTTP 标头等的属性。在本文档中,按照惯例,该对象始终称为 req(HTTP 响应为 res),但其实际名称由你正在使用的回调函数的参数确定。

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res) but its actual name is determined by the parameters to the callback function in which you’re working.

例如:

For example:

app.get('/user/:id', (req, res) => {
  res.send(`user ${req.params.id}`)
})

但你也可以拥有:

But you could just as well have:

app.get('/user/:id', (request, response) => {
  response.send(`user ${request.params.id}`)
})

req 对象是 Node 自带请求对象的增强版,支持所有 内置字段和方法

The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods.

属性

在 Express 4 中,默认情况下 req.filesreq 对象上不再可用。要访问 req.files 对象上上传的文件,请使用多部分处理中间件,例如 busboymulterformidablemultipartyconnect-multipartypez

In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty, or pez.

req.app

此属性包含对使用中间件的 Express 应用实例的引用。

This property holds a reference to the instance of the Express application that is using the middleware.

如果你遵循创建一个模块的模式,该模块仅导出一个中间件函数并在主文件中 require(),则中间件可以通过 req.app 访问 Express 实例

If you follow the pattern in which you create a module that just exports a middleware function and require() it in your main file, then the middleware can access the Express instance via req.app

例如:

For example:

// index.js
app.get('/viewdirectory', require('./mymiddleware.js'))
// mymiddleware.js
module.exports = (req, res) => {
  res.send(`The views directory is ${req.app.get('views')}`)
}

req.baseUrl

安装路由实例的 URL 路径。

The URL path on which a router instance was mounted.

req.baseUrl 属性类似于 app 对象的 mountpath 属性,除了 app.mountpath 返回匹配的路径模式。

The req.baseUrl property is similar to the mountpath property of the app object, except app.mountpath returns the matched path pattern(s).

例如:

For example:

const greet = express.Router()

greet.get('/jp', (req, res) => {
  console.log(req.baseUrl) // /greet
  res.send('Konichiwa!')
})

app.use('/greet', greet) // load the router on '/greet'

即使你使用路径模式或一组路径模式来加载路由,baseUrl 属性也会返回匹配的字符串,而不是模式。在以下示例中,greet 路由加载在两个路径模式上。

Even if you use a path pattern or a set of path patterns to load the router, the baseUrl property returns the matched string, not the pattern(s). In the following example, the greet router is loaded on two path patterns.

app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o'

当向 /greet/jp 发出请求时,req.baseUrl 是 “/greet”。当向 /hello/jp 发出请求时,req.baseUrl 是 “/hello”。

When a request is made to /greet/jp, req.baseUrl is “/greet”. When a request is made to /hello/jp, req.baseUrl is “/hello”.

req.body

包含在请求正文中提交的数据键值对。默认情况下,它是 undefined,并在你使用 body-parsermulter 等正文解析中间件时填充。

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

由于 req.body 的形状基于用户控制的输入,因此该对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能以多种方式失败,例如 foo 可能不存在或可能不是字符串,并且 toString 可能不是函数而是字符串或其他用户输入。

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

以下示例显示如何使用正文解析中间件填充 req.body

The following example shows how to use body-parsing middleware to populate req.body.

const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer') // v1.0.5
const upload = multer() // for parsing multipart/form-data

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/profile', upload.array(), (req, res, next) => {
  console.log(req.body)
  res.json(req.body)
})

req.cookies

使用 cookie-parser 中间件时,该属性是一个包含请求发送的 cookie 的对象。如果请求不包含 cookie,则默认为 {}

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

// Cookie: name=tj
console.dir(req.cookies.name)
// => "tj"

如果 cookie 已签名,则必须使用 req.signedCookies

If the cookie has been signed, you have to use req.signedCookies.

有关更多信息、问题或疑虑,请参阅 cookie-parser

For more information, issues, or concerns, see cookie-parser.

req.fresh

当客户端缓存中的响应仍然是 “fresh” 时,返回 true,否则返回 false 以指示客户端缓存现在已过时,应发送完整响应。

When the response is still “fresh” in the client’s cache true is returned, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent.

当客户端发送 Cache-Control: no-cache 请求头指示端到端的重新加载请求时,该模块将返回 false 以使处理这些请求透明。

When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent.

有关缓存验证如何工作的更多详细信息,请参阅 HTTP/1.1 缓存规范

Further details for how cache validation works can be found in the HTTP/1.1 Caching Specification.

console.dir(req.fresh)
// => true

req.host

包含从 Host HTTP 标头派生的主机。

Contains the host derived from the Host HTTP header.

trust proxy 设置 不计算为 false 时,此属性将改为从 X-Forwarded-Host 标头字段中获取值。此标头可以由客户端或代理设置。

When the trust proxy setting does not evaluate to false, this property will instead get the value from the X-Forwarded-Host header field. This header can be set by the client or by the proxy.

如果请求中有多个 X-Forwarded-Host 标头,则使用第一个标头的值。这包括一个带有逗号分隔值的标头,其中使用了第一个值。

If there is more than one X-Forwarded-Host header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

// Host: "example.com:3000"
console.dir(req.host)
// => 'example.com:3000'

// Host: "[::1]:3000"
console.dir(req.host)
// => '[::1]:3000'

req.hostname

包含从 Host HTTP 标头派生的主机名。

Contains the hostname derived from the Host HTTP header.

trust proxy 设置 不计算为 false 时,此属性将改为从 X-Forwarded-Host 标头字段中获取值。此标头可以由客户端或代理设置。

When the trust proxy setting does not evaluate to false, this property will instead get the value from the X-Forwarded-Host header field. This header can be set by the client or by the proxy.

如果请求中有多个 X-Forwarded-Host 标头,则使用第一个标头的值。这包括一个带有逗号分隔值的标头,其中使用了第一个值。

If there is more than one X-Forwarded-Host header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

在 Express v4.17.0 之前,X-Forwarded-Host 不能包含多个值或出现多次。

Prior to Express v4.17.0, the X-Forwarded-Host could not contain multiple values or be present more than once.

// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'

req.ip

包含请求的远程 IP 地址。

Contains the remote IP address of the request.

trust proxy 设置 不计算为 false 时,此属性的值派生自 X-Forwarded-For 标头中最左侧的条目。此标头可以由客户端或代理设置。

When the trust proxy setting does not evaluate to false, the value of this property is derived from the left-most entry in the X-Forwarded-For header. This header can be set by the client or by the proxy.

console.dir(req.ip)
// => "127.0.0.1"

req.ips

trust proxy 设置 不评估为 false 时,此属性包含 X-Forwarded-For 请求标头中指定的 IP 地址数组。否则,它包含一个空数组。此标头可以由客户端或代理设置。

When the trust proxy setting does not evaluate to false, this property contains an array of IP addresses specified in the X-Forwarded-For request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

例如,如果 X-Forwarded-Forclient, proxy1, proxy2,则 req.ips 将是 ["client", "proxy1", "proxy2"],其中 proxy2 是最下游的。

For example, if X-Forwarded-For is client, proxy1, proxy2, req.ips would be ["client", "proxy1", "proxy2"], where proxy2 is the furthest downstream.

req.method

包含与请求的 HTTP 方法对应的字符串:GETPOSTPUT 等等。

Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on.

req.originalUrl

req.url 不是原生 Express 属性,它是从 Node 的 http 模块 继承的。

req.url is not a native Express property, it is inherited from Node’s http module.

这个属性很像 req.url;但是,它保留了原始请求 URL,允许你出于内部路由目的自由重写 req.url。例如,app.use() 的 “mounting” 功能将重写 req.url 以剥离挂载点。

This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.

// GET /search?q=something
console.dir(req.originalUrl)
// => "/search?q=something"

req.originalUrl 在中间件和路由对象中都可用,并且是 req.baseUrlreq.url 的组合。考虑以下示例:

req.originalUrl is available both in middleware and router objects, and is a combination of req.baseUrl and req.url. Consider following example:

// GET 'http://www.example.com/admin/new?sort=desc'
app.use('/admin', (req, res, next) => {
  console.dir(req.originalUrl) // '/admin/new?sort=desc'
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  next()
})

req.params

此属性是一个包含映射到 命名路由 “参数” 的属性的对象。例如,如果你有路由 /user/:name,则 “name” 属性可用作 req.params.name。此对象默认为 {}

This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.

// GET /user/tj
console.dir(req.params.name)
// => "tj"

当你使用正则表达式进行路由定义时,将使用 req.params[n] 在数组中提供捕获组,其中 n 是第 n 个捕获组。此规则适用于带有字符串路由的未命名通配符匹配,例如 /file/*

When you use a regular expression for the route definition, capture groups are provided in the array using req.params[n], where n is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as /file/*:

// GET /file/javascripts/jquery.js
console.dir(req.params[0])
// => "javascripts/jquery.js"

如果你需要更改 req.params 中的键,请使用 app.param 处理程序。更改仅适用于已在路由路径中定义的 参数

If you need to make changes to a key in req.params, use the app.param handler. Changes are applicable only to parameters already defined in the route path.

在中间件或路由处理程序中对 req.params 对象所做的任何更改都将被重置。

Any changes made to the req.params object in a middleware or route handler will be reset.

注意:Express 自动解码 req.params 中的值(使用 decodeURIComponent)。

NOTE: Express automatically decodes the values in req.params (using decodeURIComponent).

req.path

包含请求 URL 的路径部分。

Contains the path part of the request URL.

// example.com/users?sort=desc
console.dir(req.path)
// => "/users"

当从中间件调用时,挂载点不包含在 req.path 中。详细信息请参见 app.use()

When called from a middleware, the mount point is not included in req.path. See app.use() for more details.

req.protocol

包含请求协议字符串:http 或(对于 TLS 请求)https

Contains the request protocol string: either http or (for TLS requests) https.

trust proxy 设置 不计算为 false 时,此属性将使用 X-Forwarded-Proto 标头字段的值(如果存在)。此标头可以由客户端或代理设置。

When the trust proxy setting does not evaluate to false, this property will use the value of the X-Forwarded-Proto header field if present. This header can be set by the client or by the proxy.

console.dir(req.protocol)
// => "http"

req.query

此属性是一个对象,其中包含路由中每个查询字符串参数的属性。当 查询解析器 设置为禁用时,它是一个空对象 {},否则它是配置的查询解析器的结果。

This property is an object containing a property for each query string parameter in the route. When query parser is set to disabled, it is an empty object {}, otherwise it is the result of the configured query parser.

由于 req.query 的形状基于用户控制的输入,因此该对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.query.foo.toString() 可能以多种方式失败,例如 foo 可能不存在或可能不是字符串,并且 toString 可能不是函数而是字符串或其他用户输入。

As req.query’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

可以使用 查询解析器应用设置 配置此属性的值,以按照你的应用需要的方式工作。一个非常流行的查询字符串解析器是 qs 模块,这是默认使用的。qs 模块可以通过许多设置进行配置,并且可能需要使用与默认设置不同的设置来填充 req.query

The value of this property can be configured with the query parser application setting to work how your application needs it. A very popular query string parser is the qs module, and this is used by default. The qs module is very configurable with many settings, and it may be desirable to use different settings than the default to populate req.query:

const qs = require('qs')
app.setting('query parser',
  (str) => qs.parse(str, { /* custom options */ }))

查看 查询解析器应用设置 文档以了解其他自定义选项。

Check out the query parser application setting documentation for other customization options.

req.res

此属性保存对与此 响应对象 相关的请求对象的引用。

This property holds a reference to the response object that relates to this request object.

req.route

包含当前匹配的路由,一个字符串。例如:

Contains the currently-matched route, a string. For example:

app.get('/user/:id?', (req, res) => {
  console.log(req.route)
  res.send('GET')
})

上一个片段的示例输出:

Example output from the previous snippet:

{ path: '/user/:id?',
  stack:
   [ { handle: [Function: userIdHandler],
       name: 'userIdHandler',
       params: undefined,
       path: undefined,
       keys: [],
       regexp: /^\/?$/i,
       method: 'get' } ],
  methods: { get: true } }

req.secure

如果建立了 TLS 连接,则为 true 的布尔属性。相当于以下内容:

A Boolean property that is true if a TLS connection is established. Equivalent to the following:

req.protocol === 'https'

req.signedCookies

使用 cookie-parser 中间件时,此属性包含请求发送的已签名 cookie,未签名且可供使用。签名的 cookie 驻留在不同的对象中以显示开发者的意图;否则,可能会对 req.cookie 值(很容易欺骗)进行恶意攻击。请注意,签署 cookie 不会使其成为 “hidden” 或加密;但只是防止篡改(因为用于签名的秘密是私有的)。

When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on req.cookie values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).

如果未发送签名 cookie,则该属性默认为 {}

If no signed cookies are sent, the property defaults to {}.

// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
console.dir(req.signedCookies.user)
// => "tobi"

有关更多信息、问题或疑虑,请参阅 cookie-parser

For more information, issues, or concerns, see cookie-parser.

req.stale

指示请求是否为 “旧的”,是否与 req.fresh 相反。有关详细信息,请参阅 req.fresh

Indicates whether the request is “stale,” and is the opposite of req.fresh. For more information, see req.fresh.

console.dir(req.stale)
// => true

req.subdomains

请求域名中的子域数组。

An array of subdomains in the domain name of the request.

// Host: "tobi.ferrets.example.com"
console.dir(req.subdomains)
// => ["ferrets", "tobi"]

应用属性 subdomain offset,默认为 2,用于确定子域段的开始。要更改此行为,请使用 app.set 更改其值。

The application property subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using app.set.

req.xhr

如果请求的 X-Requested-With 标头字段为 “XMLHttpRequest”,则为 true 的布尔属性,表示该请求是由 jQuery 等客户端库发出的。

A Boolean property that is true if the request’s X-Requested-With header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.

console.dir(req.xhr)
// => true

方法

req.accepts(types)

根据请求的 Accept HTTP 标头字段检查指定的内容类型是否可接受。该方法返回最佳匹配,或者如果指定的内容类型都不可接受,则返回 false(在这种情况下,应用应以 406 "Not Acceptable" 响应)。

Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns false (in which case, the application should respond with 406 "Not Acceptable").

type 值可以是单个 MIME 类型字符串(例如 “application/json”)、扩展名(例如 “json”)、逗号分隔的列表或数组。对于列表或数组,该方法返回最佳匹配(如果有)。

The type value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the best match (if any).

// Accept: text/html
req.accepts('html')
// => "html"

// Accept: text/*, application/json
req.accepts('html')
// => "html"
req.accepts('text/html')
// => "text/html"
req.accepts(['json', 'text'])
// => "json"
req.accepts('application/json')
// => "application/json"

// Accept: text/*, application/json
req.accepts('image/png')
req.accepts('png')
// => false

// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json'])
// => "json"

如需更多信息,或者如果你有问题或疑虑,请参阅 accepts

For more information, or if you have issues or concerns, see accepts.

req.acceptsCharsets(charset [, ...])

根据请求的 Accept-Charset HTTP 标头字段,返回指定字符集的第一个接受的字符集。如果不接受任何指定的字符集,则返回 false

Returns the first accepted charset of the specified character sets, based on the request’s Accept-Charset HTTP header field. If none of the specified charsets is accepted, returns false.

如需更多信息,或者如果你有问题或疑虑,请参阅 accepts

For more information, or if you have issues or concerns, see accepts.

req.acceptsEncodings(encoding [, ...])

根据请求的 Accept-Encoding HTTP 标头字段,返回指定编码的第一个接受的编码。如果不接受任何指定的编码,则返回 false

Returns the first accepted encoding of the specified encodings, based on the request’s Accept-Encoding HTTP header field. If none of the specified encodings is accepted, returns false.

如需更多信息,或者如果你有问题或疑虑,请参阅 accepts

For more information, or if you have issues or concerns, see accepts.

req.acceptsLanguages(lang [, ...])

根据请求的 Accept-Language HTTP 标头字段,返回指定语言中第一个接受的语言。如果不接受任何指定的语言,则返回 false

Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field. If none of the specified languages is accepted, returns false.

如需更多信息,或者如果你有问题或疑虑,请参阅 accepts

For more information, or if you have issues or concerns, see accepts.

req.get(field)

返回指定的 HTTP 请求头字段(不区分大小写的匹配)。ReferrerReferer 字段可以互换。

Returns the specified HTTP request header field (case-insensitive match). The Referrer and Referer fields are interchangeable.

req.get('Content-Type')
// => "text/plain"

req.get('content-type')
// => "text/plain"

req.get('Something')
// => undefined

别名为 req.header(field)

Aliased as req.header(field).

req.is(type)

如果传入请求的 “Content-Type” HTTP 标头字段与 type 参数指定的 MIME 类型匹配,则返回匹配的内容类型。如果请求没有正文,则返回 null。否则返回 false

Returns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the type parameter. If the request has no body, returns null. Returns false otherwise.

// With Content-Type: text/html; charset=utf-8
req.is('html') // => 'html'
req.is('text/html') // => 'text/html'
req.is('text/*') // => 'text/*'

// When Content-Type is application/json
req.is('json') // => 'json'
req.is('application/json') // => 'application/json'
req.is('application/*') // => 'application/*'

req.is('html')
// => false

如需更多信息,或者如果你有问题或疑虑,请参阅 type-is

For more information, or if you have issues or concerns, see type-is.

req.range(size[, options])

Range 标头解析器。

Range header parser.

size 参数是资源的最大大小。

The size parameter is the maximum size of the resource.

options 参数是一个可以具有以下属性的对象。

The options parameter is an object that can have the following properties.

Property Type Description
combine Boolean Specify if overlapping & adjacent ranges should be combined, defaults to false. When true, ranges will be combined and returned as if they were specified that way in the header.

将返回一个范围数组或指示解析错误的负数。

An array of ranges will be returned or negative numbers indicating an error parsing.

  • -2 表示格式错误的标头字符串

    -2 signals a malformed header string

  • -1 表示无法满足的范围

    -1 signals an unsatisfiable range

// parse header from request
const range = req.range(1000)

// the type of the range
if (range.type === 'bytes') {
  // the ranges
  range.forEach((r) => {
    // do something with r.start and r.end
  })
}

响应

res 对象表示 Express 应用在收到 HTTP 请求时发送的 HTTP 响应。

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

在本文档中,按照惯例,该对象始终称为 res(HTTP 请求为 req),但其实际名称由你正在使用的回调函数的参数确定。

In this documentation and by convention, the object is always referred to as res (and the HTTP request is req) but its actual name is determined by the parameters to the callback function in which you’re working.

例如:

For example:

app.get('/user/:id', (req, res) => {
  res.send(`user ${req.params.id}`)
})

但你也可以拥有:

But you could just as well have:

app.get('/user/:id', (request, response) => {
  response.send(`user ${request.params.id}`)
})

res 对象是 Node 自带响应对象的增强版,支持所有 内置字段和方法

The res object is an enhanced version of Node’s own response object and supports all built-in fields and methods.

属性

res.app

此属性包含对使用中间件的 Express 应用实例的引用。

This property holds a reference to the instance of the Express application that is using the middleware.

res.app 与请求对象中的 req.app 属性相同。

res.app is identical to the req.app property in the request object.

res.headersSent

指示应用是否为响应发送 HTTP 标头的布尔属性。

Boolean property that indicates if the app sent HTTP headers for the response.

app.get('/', (req, res) => {
  console.log(res.headersSent) // false
  res.send('OK')
  console.log(res.headersSent) // true
})

res.locals

使用此属性设置在使用 res.render 渲染的模板中可访问的变量。res.locals 上设置的变量在单个请求-响应周期内可用,并且不会在请求之间共享。

Use this property to set variables accessible in templates rendered with res.render. The variables set on res.locals are available within a single request-response cycle, and will not be shared between requests.

为了保留局部变量以用于请求之间的模板渲染,请改用 app.locals

In order to keep local variables for use in template rendering between requests, use app.locals instead.

此属性对于向应用中渲染的模板公开请求级信息(例如请求路径名称、经过身份验证的用户、用户设置等)很有用。

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.

app.use((req, res, next) => {
  // Make `user` and `authenticated` available in templates
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})

res.req

该属性保存对与该 请求对象 相关的响应对象的引用。

This property holds a reference to the request object that relates to this response object.

方法

res.append(field [, value])

Express v4.11.0+ 支持 res.append()

res.append() is supported by Express v4.11.0+

将指定的 value 附加到 HTTP 响应标头 field。如果尚未设置标头,则会创建具有指定值的标头。value 参数可以是字符串或数组。

Appends the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

注意:在 res.append() 之后调用 res.set() 将重置先前设置的标头值。

Note: calling res.set() after res.append() will reset the previously-set header value.

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly')
res.append('Warning', '199 Miscellaneous warning')

res.attachment([filename])

将 HTTP 响应 Content-Disposition 标头字段设置为 “attachment”。如果给出了 filename,那么它会根据扩展名通过 res.type() 设置 Content-Type,并设置 Content-Disposition “filename=” 参数。

Sets the HTTP response Content-Disposition header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via res.type(), and sets the Content-Disposition “filename=” parameter.

res.attachment()
// Content-Disposition: attachment

res.attachment('path/to/logo.png')
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png

res.cookie(name, value [, options])

将 cookie name 设置为 valuevalue 参数可以是字符串或转换为 JSON 的对象。

Sets cookie name to value. The value parameter may be a string or object converted to JSON.

options 参数是一个可以具有以下属性的对象。

The options parameter is an object that can have the following properties.

Property Type Description
domain String Domain name for the cookie. Defaults to the domain name of the app.
encode Function A synchronous function used for cookie value encoding. Defaults to encodeURIComponent.
expires Date Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.
httpOnly Boolean Flags the cookie to be accessible only by the web server.
maxAge Number Convenient option for setting the expiry time relative to the current time in milliseconds.
path String Path for the cookie. Defaults to “/”.
secure Boolean Marks the cookie to be used with HTTPS only.
signed Boolean Indicates if the cookie should be signed.
sameSite Boolean or String Value of the “SameSite” Set-Cookie attribute. More information at https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1.

res.cookie() 所做的只是使用提供的选项设置 HTTP Set-Cookie 标头。任何未指定的选项默认为 RFC 6265 中指定的值。

All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.

例如:

For example:

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })

encode 选项允许你选择用于 cookie 值编码的函数。不支持异步函数。

The encode option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.

示例用例:你需要为组织中的另一个站点设置域范围的 cookie。此其他站点(不受你的管理控制)不使用 URI 编码的 cookie 值。

Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.

// Default encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' })
// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'

// Custom encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String })
// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'

maxAge 选项是一个方便的选项,用于设置 “expires” 相对于当前时间(以毫秒为单位)。以下等效于上面的第二个示例。

The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.

res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })

你可以传递一个对象作为 value 参数;然后它被序列化为 JSON 并由 bodyParser() 中间件解析。

You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.

res.cookie('cart', { items: [1, 2, 3] })
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })

使用 cookie-parser 中间件时,此方法还支持签名 cookie。只需将 signed 选项设置为 true。然后 res.cookie() 将使用传递给 cookieParser(secret) 的秘密对值进行签名。

When using cookie-parser middleware, this method also supports signed cookies. Simply include the signed option set to true. Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.

res.cookie('name', 'tobi', { signed: true })

稍后你可以通过 req.signedCookies 对象访问此值。

Later you may access this value through the req.signedCookies object.

res.clearCookie(name [, options])

清除 name 指定的 cookie。关于 options 对象的详细信息,请参见 res.cookie()

Clears the cookie specified by name. For details about the options object, see res.cookie().

仅当给定的 options 与给定的 res.cookie() 相同(不包括 expiresmaxAge)时,Web 浏览器和其他兼容客户端才会清除 cookie。

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

res.cookie('name', 'tobi', { path: '/admin' })
res.clearCookie('name', { path: '/admin' })

res.download(path [, filename] [, options] [, fn])

Express v4.16.0 及以上版本支持可选的 options 参数。

The optional options argument is supported by Express v4.16.0 onwards.

path 处的文件作为 “attachment” 传输。通常,浏览器会提示用户下载。默认情况下,Content-Disposition 标头 “filename=” 参数源自 path 参数,但可以使用 filename 参数覆盖。如果 path 是相对的,那么它将基于进程的当前工作目录。

Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is derived from the path argument, but can be overridden with the filename parameter. If path is relative, then it will be based on the current working directory of the process.

下表提供了有关 options 参数的详细信息。

The following table provides details on the options parameter.

Express v4.16.0 及以上版本支持可选的 options 参数。

The optional options argument is supported by Express v4.16.0 onwards.

属性 描述 默认 可用性
maxAge 设置 Cache-Control 标头的 max-age 属性(以毫秒为单位)或 ms 格式 中的字符串 0 4.16+
lastModified Last-Modified 标头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。 启用 4.16+
headers 包含与文件一起服务的 HTTP 标头的对象。标头 Content-Disposition 将被 filename 参数覆盖。   4.16+
dotfiles 提供点文件的选项。可能的值为 “allow”、”deny”、”ignore”。 “ignore” 4.16+
acceptRanges 启用或禁用接受范围请求。 true 4.16+
cacheControl 启用或禁用设置 Cache-Control 响应标头。 true 4.16+
immutable Cache-Control 响应标头中启用或禁用 immutable 指令。如果启用,还应指定 maxAge 选项以启用缓存。immutable 指令将阻止受支持的客户端在 maxAge 选项的生命周期内发出条件请求以检查文件是否已更改。 false 4.16+

该方法在传输完成或发生错误时调用回调函数 fn(err)。如果指定了回调函数并且发生错误,则回调函数必须通过结束请求-响应循环或将控制权传递给下一个路由来显式处理响应过程。

The method invokes the callback function fn(err) when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.

res.download('/report-12345.pdf')

res.download('/report-12345.pdf', 'report.pdf')

res.download('/report-12345.pdf', 'report.pdf', (err) => {
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
})

res.end([data] [, encoding])

结束响应过程。这个方法实际上来自 Node 核心,特别是 http.ServerResponse 的 response.end() 方法

Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.

用于在没有任何数据的情况下快速结束响应。如果你需要用数据响应,请改用 res.send()res.json() 等方法。

Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

res.end()
res.status(404).end()

res.format(object)

对请求对象的 Accept HTTP 标头(如果存在)执行内容协商。它使用 req.accepts() 根据质量值排序的可接受类型为请求选择处理程序。如果未指定标头,则调用第一个回调。当未找到匹配项时,服务器响应 406 “不接受”,或调用 default 回调。

Performs content-negotiation on the Accept HTTP header on the request object, when present. It uses req.accepts() to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the default callback.

选择回调时设置 Content-Type 响应标头。但是,你可以使用 res.set()res.type() 等方法在回调中更改它。

The Content-Type response header is set when a callback is selected. However, you may alter this within the callback using methods such as res.set() or res.type().

Accept 头字段设置为 “application/json” 或 “*/json” 时,以下示例将响应 { "message": "hey" }(但是如果它是 “/”,则响应将为 “hey”)。

The following example would respond with { "message": "hey" } when the Accept header field is set to “application/json” or “*/json” (however if it is “*/*”, then the response will be “hey”).

res.format({
  'text/plain' () {
    res.send('hey')
  },

  'text/html' () {
    res.send('<p>hey</p>')
  },

  'application/json' () {
    res.send({ message: 'hey' })
  },

  default () {
    // log the request and respond with 406
    res.status(406).send('Not Acceptable')
  }
})

除了规范化的 MIME 类型之外,你还可以使用映射到这些类型的扩展名来实现稍微不那么冗长的实现:

In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:

res.format({
  text () {
    res.send('hey')
  },

  html () {
    res.send('<p>hey</p>')
  },

  json () {
    res.send({ message: 'hey' })
  }
})

res.get(field)

返回 field 指定的 HTTP 响应标头。匹配不区分大小写。

Returns the HTTP response header specified by field. The match is case-insensitive.

res.get('Content-Type')
// => "text/plain"

res.json([body])

发送 JSON 响应。此方法发送一个响应(具有正确的内容类型),该响应是使用 JSON.stringify() 转换为 JSON 字符串的参数。

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

参数可以是任何 JSON 类型,包括对象、数组、字符串、布尔值、数字或 null,你也可以使用它来将其他值转换为 JSON。

The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

res.jsonp([body])

发送带有 JSONP 支持的 JSON 响应。此方法与 res.json() 相同,只是它选择加入 JSONP 回调支持。

Sends a JSON response with JSONP support. This method is identical to res.json(), except that it opts-in to JSONP callback support.

res.jsonp(null)
// => callback(null)

res.jsonp({ user: 'tobi' })
// => callback({ "user": "tobi" })

res.status(500).jsonp({ error: 'message' })
// => callback({ "error": "message" })

默认情况下,JSONP 回调名称只是 callback。使用 jsonp 回调名称 设置覆盖此设置。

By default, the JSONP callback name is simply callback. Override this with the jsonp callback name setting.

以下是使用相同代码的 JSONP 响应的一些示例:

The following are some examples of JSONP responses using the same code:

// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })

app.set('jsonp callback name', 'cb')

// ?cb=foo
res.status(500).jsonp({ error: 'message' })
// => foo({ "error": "message" })

加入作为参数属性提供的 links 以填充响应的 Link HTTP 标头字段。

Joins the links provided as properties of the parameter to populate the response’s Link HTTP header field.

例如,以下调用:

For example, the following call:

res.links({
  next: 'http://api.example.com/users?page=2',
  last: 'http://api.example.com/users?page=5'
})

产生以下结果:

Yields the following results:

Link: <http://api.example.com/users?page=2>; rel="next",
      <http://api.example.com/users?page=5>; rel="last"

res.location(path)

将响应 Location HTTP 标头设置为指定的 path 参数。

Sets the response Location HTTP header to the specified path parameter.

res.location('/foo/bar')
res.location('http://example.com')
res.location('back')

path 值 “back” 有特殊含义,它指的是请求的 Referer 标头中指定的 URL。如果未指定 Referer 标头,则它引用 “/”。

A path value of “back” has a special meaning, it refers to the URL specified in the Referer header of the request. If the Referer header was not specified, it refers to “/”.

After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header, without any validation.

浏览器负责从当前 URL 或引用 URL 以及 Location 标头中指定的 URL 派生出预期的 URL;并相应地重定向用户。

Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.

res.redirect([status,] path)

重定向到从指定 path 派生的 URL,并指定 status(对应于 HTTP 状态码 的正整数)。 如果未指定,status 默认为 “302”Found”。

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.

res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')

重定向可以是用于重定向到不同站点的完全限定 URL:

Redirects can be a fully-qualified URL for redirecting to a different site:

res.redirect('http://google.com')

重定向可以相对于主机名的根目录。例如,如果应用位于 http://example.com/admin/post/new 上,则以下内容将重定向到 URL http://example.com/admin

Redirects can be relative to the root of the host name. For example, if the application is on http://example.com/admin/post/new, the following would redirect to the URL http://example.com/admin:

res.redirect('/admin')

重定向可以相对于当前 URL。例如,从 http://example.com/blog/admin/(注意尾部斜杠)开始,以下内容将重定向到 URL http://example.com/blog/admin/post/new

Redirects can be relative to the current URL. For example, from http://example.com/blog/admin/ (notice the trailing slash), the following would redirect to the URL http://example.com/blog/admin/post/new.

res.redirect('post/new')

http://example.com/blog/admin 重定向到 post/new(没有尾部斜杠),将重定向到 http://example.com/blog/post/new

Redirecting to post/new from http://example.com/blog/admin (no trailing slash), will redirect to http://example.com/blog/post/new.

如果你发现上述行为令人困惑,请将路径段视为目录(带有尾部斜杠)和文件,这将开始有意义。

If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

路径相关的重定向也是可能的。如果你在 http://example.com/admin/post/new,以下将重定向到 http://example.com/admin/post

Path-relative redirects are also possible. If you were on http://example.com/admin/post/new, the following would redirect to http://example.com/admin/post:

res.redirect('..')

back 重定向将请求重定向回 referer,当引用者丢失时默认为 /

A back redirection redirects the request back to the referer, defaulting to / when the referer is missing.

res.redirect('back')

res.render(view [, locals] [, callback])

渲染 view 并将渲染的 HTML 字符串发送到客户端。可选参数:

Renders a view and sends the rendered HTML string to the client. Optional parameters:

  • locals,一个对象,其属性定义视图的局部变量。

    locals, an object whose properties define local variables for the view.

  • callback,回调函数。如果提供,该方法将返回可能的错误和渲染的字符串,但不执行自动响应。当发生错误时,该方法在内部调用 next(err)

    callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

view 参数是一个字符串,它是要渲染的视图文件的文件路径。这可以是绝对路径,也可以是相对于 views 设置的路径。如果路径不包含文件扩展名,则 view engine 设置确定文件扩展名。如果路径确实包含文件扩展名,那么 Express 将加载指定模板引擎的模块(通过 require())并使用加载模块的 __express 函数渲染它。

The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via require()) and render it using the loaded module’s __express function.

有关详细信息,请参阅 使用 Express 模板引擎

For more information, see Using template engines with Express.

注意:view 参数执行文件系统操作,例如从磁盘读取文件和评估 Node.js 模块,因此出于安全原因不应包含来自终端用户的输入。

NOTE: The view argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.

局部变量 cache 启用视图缓存。设置为 true,用于在开发过程中缓存视图;默认情况下,在生产环境中启用视图缓存。

The local variable cache enables view caching. Set it to true, to cache the view during development; view caching is enabled in production by default.

// send the rendered view to the client
res.render('index')

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', (err, html) => {
  res.send(html)
})

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, (err, html) => {
  // ...
})

res.send([body])

发送 HTTP 响应。

Sends the HTTP response.

body 参数可以是 Buffer 对象、String、对象、BooleanArray。例如:

The body parameter can be a Buffer object, a String, an object, Boolean, or an Array. For example:

res.send(Buffer.from('whoop'))
res.send({ some: 'json' })
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({ error: 'something blew up' })

此方法对简单的非流式响应执行许多有用的任务:例如,它自动分配 Content-Length HTTP 响应头字段(除非之前定义)并提供自动 HEAD 和 HTTP 缓存新鲜度支持。

This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

当参数是 Buffer 对象时,该方法将 Content-Type 响应头字段设置为 “application/octet-stream”,除非之前定义如下:

When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:

res.set('Content-Type', 'text/html')
res.send(Buffer.from('<p>some html</p>'))

当参数为 String 时,该方法将 Content-Type 设置为 “text/html”:

When the parameter is a String, the method sets the Content-Type to “text/html”:

res.send('<p>some html</p>')

当参数为 ArrayObject 时,Express 以 JSON 表示形式响应:

When the parameter is an Array or Object, Express responds with the JSON representation:

res.send({ user: 'tobi' })
res.send([1, 2, 3])

res.sendFile(path [, options] [, fn])

Express v4.8.0 及以上版本支持 res.sendFile()

res.sendFile() is supported by Express v4.8.0 onwards.

在给定的 path 传输文件。根据文件名的扩展名设置 Content-Type 响应 HTTP 标头字段。除非在选项对象中设置了 root 选项,否则 path 必须是文件的绝对路径。

Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.

此 API 提供对正在运行的文件系统上的数据的访问。确保 (a) 如果包含用户输入,将 path 参数构造为绝对路径的方式是安全的,或者 (b) 将 root 选项设置为包含访问权限的目录的绝对路径。

This API provides access to data on the running file system. Ensure that either (a) the way in which the path argument was constructed into an absolute path is secure if it contains user input or (b) set the root option to the absolute path of a directory to contain access within.

当提供 root 选项时,允许 path 参数为相对路径,包括包含 ..。Express 将验证作为 path 提供的相对路径将在给定的 root 选项中解析。

When the root option is provided, the path argument is allowed to be a relative path, including containing ... Express will validate that the relative path provided as path will resolve within the given root option.

下表提供了有关 options 参数的详细信息。

The following table provides details on the options parameter.

属性 描述 默认 可用性
maxAge 设置 Cache-Control 标头的 max-age 属性(以毫秒为单位)或 ms 格式 中的字符串 0  
root 相对文件名的根目录。    
lastModified Last-Modified 标头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。 启用 4.9.0+
headers 包含与文件一起服务的 HTTP 标头的对象。    
dotfiles 提供点文件的选项。可能的值为 “allow”、”deny”、”ignore”。 “ignore”  
acceptRanges 启用或禁用接受范围请求。 true 4.14+
cacheControl 启用或禁用设置 Cache-Control 响应标头。 true 4.14+
immutable Cache-Control 响应标头中启用或禁用 immutable 指令。如果启用,还应指定 maxAge 选项以启用缓存。immutable 指令将阻止受支持的客户端在 maxAge 选项的生命周期内发出条件请求以检查文件是否已更改。 false 4.16+

该方法在传输完成或发生错误时调用回调函数 fn(err)。如果指定了回调函数并且发生错误,则回调函数必须通过结束请求-响应循环或将控制权传递给下一个路由来显式处理响应过程。

The method invokes the callback function fn(err) when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.

这是一个使用 res.sendFile 及其所有参数的示例。

Here is an example of using res.sendFile with all its arguments.

app.get('/file/:name', (req, res, next) => {
  const options = {
    root: path.join(__dirname, 'public'),
    dotfiles: 'deny',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  }

  const fileName = req.params.name
  res.sendFile(fileName, options, (err) => {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', fileName)
    }
  })
})

以下示例说明了使用 res.sendFile 为服务文件提供细粒度支持:

The following example illustrates using res.sendFile to provide fine-grained support for serving files:

app.get('/user/:uid/photos/:file', (req, res) => {
  const uid = req.params.uid
  const file = req.params.file

  req.user.mayViewFilesFrom(uid, (yes) => {
    if (yes) {
      res.sendFile(`/uploads/${uid}/${file}`)
    } else {
      res.status(403).send("Sorry! You can't see that.")
    }
  })
})

如需更多信息,或者如果你有问题或疑虑,请参阅 send

For more information, or if you have issues or concerns, see send.

res.sendStatus(statusCode)

将响应 HTTP 状态代码设置为 statusCode,并将注册的状态消息作为文本响应正文发送。如果指定了未知状态代码,则响应正文将只是代码编号。

Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

res.sendStatus(404)

res.statusCode 设置为无效的 HTTP 状态代码(超出 100599 范围)时,某些版本的 Node.js 会抛出异常。请参阅 HTTP 服务器文档以了解所使用的 Node.js 版本。

Some versions of Node.js will throw when res.statusCode is set to an invalid HTTP status code (outside of the range 100 to 599). Consult the HTTP server documentation for the Node.js version being used.

更多关于 HTTP 状态码

More about HTTP Status Codes

res.set(field [, value])

将响应的 HTTP 标头 field 设置为 value。要一次设置多个字段,请将对象作为参数传递。

Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.

res.set('Content-Type', 'text/plain')

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  ETag: '12345'
})

别名为 res.header(field [, value])

Aliased as res.header(field [, value]).

res.status(code)

设置响应的 HTTP 状态。它是 Node 的 response.statusCode 的可链式别名。

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

res.type(type)

Content-Type HTTP 标头设置为由指定 type 确定的 MIME 类型。如果 type 包含 “/” 字符,则它将 Content-Type 设置为 type 的精确值,否则假定它是文件扩展名,并使用 express.static.mime.lookup() 方法在映射中查找 MIME 类型。

Sets the Content-Type HTTP header to the MIME type as determined by the specified type. If type contains the “/” character, then it sets the Content-Type to the exact value of type, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the express.static.mime.lookup() method.

res.type('.html') // => 'text/html'
res.type('html') // => 'text/html'
res.type('json') // => 'application/json'
res.type('application/json') // => 'application/json'
res.type('png') // => image/png:

res.vary(field)

将该字段添加到 Vary 响应标头(如果尚不存在)。

Adds the field to the Vary response header, if it is not there already.

res.vary('User-Agent').render('docs')

路由

A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.

路由的行为类似于中间件本身,因此你可以将其用作 app.use() 的参数或另一个路由的 use() 方法的参数。

A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.

顶层 express 对象具有创建新 router 对象的 Router() 方法。

The top-level express object has a Router() method that creates a new router object.

一旦你创建了一个路由对象,你就可以像应用一样向它添加中间件和 HTTP 方法路由(例如 getputpost 等)。例如:

Once you’ve created a router object, you can add middleware and HTTP method routes (such as get, put, post, and so on) to it just like an application. For example:

// invoked for any requests passed to this router
router.use((req, res, next) => {
  // .. some logic here .. like any other middleware
  next()
})

// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', (req, res, next) => {
  // ..
})

然后,你可以将路由用于特定的根 URL,以这种方式将你的路由分成文件甚至迷你应用。

You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.

// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router)

方法

router.all(path, [callback, ...] callback)

此方法与 router.METHOD() 方法一样,只是它匹配所有 HTTP 方法(动词)。

This method is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs).

此方法对于为特定路径前缀或任意匹配映射 “global” 逻辑非常有用。例如,如果你将以下路由放在所有其他路由定义的顶部,则要求从该点开始的所有路由都需要身份验证,并自动加载用户。请记住,这些回调不必充当端点;loadUser 可以执行一个任务,然后调用 next() 继续匹配后续路由。

This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next() to continue matching subsequent routes.

router.all('*', requireAuthentication, loadUser)

或等价物:

Or the equivalent:

router.all('*', requireAuthentication)
router.all('*', loadUser)

另一个例子是列入白名单的 “global” 功能。这里的例子很像以前,但它只限制以 “/api” 为前缀的路径:

Another example of this is white-listed “global” functionality. Here the example is much like before, but it only restricts paths prefixed with “/api”:

router.all('/api/*', requireAuthentication)

router.METHOD(path, [callback, ...] callback)

router.METHOD() 方法在 Express 中提供路由功能,其中 METHOD 是 HTTP 方法之一,例如 GET、PUT、POST 等,小写。因此,实际的方法是 router.get()router.post()router.put() 等等。

The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are router.get(), router.post(), router.put(), and so on.

如果在 router.get() 之前没有为路径调用 router.head(),除了 GET 方法之外,还会自动为 HTTP HEAD 方法调用 router.get() 函数。

The router.get() function is automatically called for the HTTP HEAD method in addition to the GET method if router.head() was not called for the path before router.get().

你可以提供多个回调,并且所有回调都被平等对待,并且表现得像中间件,除了这些回调可能会调用 next('route') 以绕过剩余的路由回调。你可以使用此机制对路由执行前置条件,然后在没有理由继续匹配路由时将控制权传递给后续路由。

You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.

以下片段说明了可能的最简单的路由定义。Express 将路径字符串转换为正则表达式,在内部用于匹配传入的请求。执行这些匹配时不考虑查询字符串,例如 “GET /” 将匹配以下路由,”GET /?name=tobi” 也是如此。

The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.

router.get('/', (req, res) => {
  res.send('hello world')
})

你还可以使用正则表达式 - 如果你有非常具体的约束,则非常有用,例如以下内容将匹配 “GET /commits/71dbb9c” 和 “GET /commits/71dbb9c..4c084f9”。

You can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c” as well as “GET /commits/71dbb9c..4c084f9”.

router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => {
  const from = req.params[0]
  const to = req.params[1] || 'HEAD'
  res.send(`commit range ${from}..${to}`)
})

你可以使用 next 基础类型根据特定的程序状态在不同的中间件函数之间实现流控制。使用字符串 'router' 调用 next 将导致该路由上所有剩余的路由回调被绕过。

You can use next primitive to implement a flow control between different middleware functions, based on a specific program state. Invoking next with the string 'router' will cause all the remaining route callbacks on that router to be bypassed.

以下示例说明了 next('router') 的用法。

The following example illustrates next('router') usage.

function fn (req, res, next) {
  console.log('I come here')
  next('router')
}
router.get('/foo', fn, (req, res, next) => {
  console.log('I dont come here')
})
router.get('/foo', (req, res, next) => {
  console.log('I dont come here')
})
app.get('/foo', (req, res) => {
  console.log(' I come here too')
  res.end('good')
})

router.param(name, callback)

为路由参数添加回调触发器,其中 name 为参数名称,callback 为回调函数。尽管 name 在技术上是可选的,但从 Express v4.11.0 开始不推荐使用此方法(见下文)。

Adds callback triggers to route parameters, where name is the name of the parameter and callback is the callback function. Although name is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).

回调函数的参数为​​:

The parameters of the callback function are:

  • req,请求对象。

    req, the request object.

  • res,响应对象。

    res, the response object.

  • next,表示下一个中间件函数。

    next, indicating the next middleware function.

  • name 参数的值。

    The value of the name parameter.

  • 参数的名称。

    The name of the parameter.

app.param() 不同,router.param() 不接受路由参数数组。

Unlike app.param(), router.param() does not accept an array of route parameters.

例如,当 :user 出现在路由路径中时,你可以映射用户加载逻辑以自动将 req.user 提供给路由,或对参数输入执行验证。

For example, when :user is present in a route path, you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

router.param('user', (req, res, next, id) => {
  // try to get the user details from the User model and attach it to the request object
  User.find(id, (err, user) => {
    if (err) {
      next(err)
    } else if (user) {
      req.user = user
      next()
    } else {
      next(new Error('failed to load user'))
    }
  })
})

参数回调函数在定义它们的路由上是本地的。它们不会被安装的应用或路由继承。因此,在 router 上定义的参数回调将仅由在 router 路由上定义的路由参数触发。

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on router will be triggered only by route parameters defined on router routes.

一个参数回调在请求-响应周期中只会被调用一次,即使该参数在多个路由中匹配,如下例所示。

A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

router.param('id', (req, res, next, id) => {
  console.log('CALLED ONLY ONCE')
  next()
})

router.get('/user/:id', (req, res, next) => {
  console.log('although this matches')
  next()
})

router.get('/user/:id', (req, res) => {
  console.log('and this matches too')
  res.end()
})

GET /user/42 上,打印以下内容:

On GET /user/42, the following is printed:

CALLED ONLY ONCE
although this matches
and this matches too

以下部分介绍了 router.param(callback),它从 v4.11.0 开始已弃用。

The following section describes router.param(callback), which is deprecated as of v4.11.0.

router.param(name, callback) 方法的行为可以通过只向 router.param() 传递一个函数来完全改变。该函数是 router.param(name, callback) 行为方式的自定义实现 - 它接受两个参数并且必须返回一个中间件。

The behavior of the router.param(name, callback) method can be altered entirely by passing only a function to router.param(). This function is a custom implementation of how router.param(name, callback) should behave - it accepts two parameters and must return a middleware.

此函数的第一个参数是应捕获的 URL 参数的名称,第二个参数可以是任何可能用于返回中间件实现的 JavaScript 对象。

The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.

函数返回的中间件决定了捕获 URL 参数时发生的行为。

The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.

在此示例中,将 router.param(name, callback) 签名修改为 router.param(name, accessId)router.param() 现在将接受名称和号码,而不是接受名称和回调。

In this example, the router.param(name, callback) signature is modified to router.param(name, accessId). Instead of accepting a name and a callback, router.param() will now accept a name and a number.

const express = require('express')
const app = express()
const router = express.Router()

// customizing the behavior of router.param()
router.param((param, option) => {
  return (req, res, next, val) => {
    if (val === option) {
      next()
    } else {
      res.sendStatus(403)
    }
  }
})

// using the customized router.param()
router.param('id', 1337)

// route to trigger the capture
router.get('/user/:id', (req, res) => {
  res.send('OK')
})

app.use(router)

app.listen(3000, () => {
  console.log('Ready')
})

在此示例中,router.param(name, callback) 签名保持不变,但没有使用中间件回调,而是定义了自定义数据类型检查函数来验证用户 ID 的数据类型。

In this example, the router.param(name, callback) signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.

router.param((param, validator) => {
  return (req, res, next, val) => {
    if (validator(val)) {
      next()
    } else {
      res.sendStatus(403)
    }
  }
})

router.param('id', (candidate) => {
  return !isNaN(parseFloat(candidate)) && isFinite(candidate)
})

router.route(path)

返回单个路由的实例,然后你可以使用该实例处理带有可选中间件的 HTTP 动词。使用 router.route() 来避免重复的路由命名,从而避免输入错误。

Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use router.route() to avoid duplicate route naming and thus typing errors.

在上面的 router.param() 示例的基础上,以下代码显示了如何使用 router.route() 来指定各种 HTTP 方法处理程序。

Building on the router.param() example above, the following code shows how to use router.route() to specify various HTTP method handlers.

const router = express.Router()

router.param('user_id', (req, res, next, id) => {
  // sample user, would actually fetch from DB, etc...
  req.user = {
    id,
    name: 'TJ'
  }
  next()
})

router.route('/users/:user_id')
  .all((req, res, next) => {
  // runs for all HTTP verbs first
  // think of it as route specific middleware!
    next()
  })
  .get((req, res, next) => {
    res.json(req.user)
  })
  .put((req, res, next) => {
  // just an example of maybe updating the user
    req.user.name = req.params.name
    // save user ... etc
    res.json(req.user)
  })
  .post((req, res, next) => {
    next(new Error('not implemented'))
  })
  .delete((req, res, next) => {
    next(new Error('not implemented'))
  })

此方法重用单个 /users/:user_id 路径并为各种 HTTP 方法添加处理程序。

This approach re-uses the single /users/:user_id path and adds handlers for various HTTP methods.

注意:当你使用 router.route() 时,中间件排序基于创建路由的时间,而不是基于方法处理程序添加到路由的时间。为此,你可以考虑方法处理程序属于添加它们的路由。

NOTE: When you use router.route(), middleware ordering is based on when the route is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added.

router.use([path], [function, ...] function)

使用指定的中间件函数或函数,带有可选的挂载路径 path,默认为 “/”。

Uses the specified middleware function or functions, with optional mount path path, that defaults to “/”.

此方法与 app.use() 类似。下面描述了一个简单的示例和用例。有关详细信息,请参阅 app.use()

This method is similar to app.use(). A simple example and use case is described below. See app.use() for more information.

中间件就像一个水管:请求从定义的第一个中间件函数开始,并按照 “down” 中间件堆栈处理它们匹配的每个路径的方式工作。

Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match.

const express = require('express')
const app = express()
const router = express.Router()

// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use((req, res, next) => {
  console.log('%s %s %s', req.method, req.url, req.path)
  next()
})

// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', (req, res, next) => {
  // ... maybe some additional /bar logging ...
  next()
})

// always invoked
router.use((req, res, next) => {
  res.send('Hello World')
})

app.use('/foo', router)

app.listen(3000)

“mount” 路径被剥离并且对中间件函数不可见。此功能的主要效果是挂载的中间件函数可以在不更改代码的情况下运行,无论其 “prefix” 路径名如何。

The “mount” path is stripped and is not visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” pathname.

使用 router.use() 定义中间件的顺序非常重要。它们按顺序调用,因此顺序定义了中间件优先级。例如,通常日志器是你将使用的第一个中间件,以便记录每个请求。

The order in which you define middleware with router.use() is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged.

const logger = require('morgan')

router.use(logger())
router.use(express.static(path.join(__dirname, 'public')))
router.use((req, res) => {
  res.send('Hello')
})

现在假设你想忽略对静态文件的日志记录请求,但继续记录 logger() 之后定义的路由和中间件。在添加日志器中间件之前,你只需将对 express.static() 的调用移至顶部:

Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after logger(). You would simply move the call to express.static() to the top, before adding the logger middleware:

router.use(express.static(path.join(__dirname, 'public')))
router.use(logger())
router.use((req, res) => {
  res.send('Hello')
})

另一个例子是从多个目录提供文件,让 “./public” 优先于其他:

Another example is serving files from multiple directories, giving precedence to “./public” over the others:

app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))

router.use() 方法还支持命名参数,因此你的其他路由的挂载点可以从使用命名参数的预加载中受益。

The router.use() method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.

注意:尽管这些中间件函数是通过特定的路由添加的,但它们运行时是由它们所连接的路径(而不是路由)定义的。因此,如果路由匹配,通过一个路由添加的中间件可以为其他路由运行。例如,此代码显示了安装在同一路径上的两个不同路由:

NOTE: Although these middleware functions are added via a particular router, when they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path:

const authRouter = express.Router()
const openRouter = express.Router()

authRouter.use(require('./authenticate').basic(usersdb))

authRouter.get('/:user_id/edit', (req, res, next) => {
  // ... Edit user UI ...
})
openRouter.get('/', (req, res, next) => {
  // ... List users ...
})
openRouter.get('/:user_id', (req, res, next) => {
  // ... View user ...
})

app.use('/users', authRouter)
app.use('/users', openRouter)

即使身份验证中间件是通过 authRouter 添加的,它也会在 openRouter 定义的路由上运行,因为两个路由都安装在 /users 上。为避免此行为,请为每个路由使用不同的路径。

Even though the authentication middleware was added via the authRouter it will run on the routes defined by the openRouter as well since both routers were mounted on /users. To avoid this behavior, use different paths for each router.