5.x API
Note 注意
Express 5.0 requires Node.js 18 or higher.
express()
Creates an Express application. The express()
function is a top-level function exported by the express
module.
创建一个 Express 应用。 express()
函数是由 express
模块导出的顶级函数。
const express = require('express')
const app = express()
Methods 方法
express.json([options]) express.json([选项])
This is a built-in middleware function in Express. It parses incoming requests
with JSON payloads and is based on
body-parser.
这是 Express 中的一个内置中间件函数。它解析带有 JSON 负载的传入请求,基于 body-parser。
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.
返回一个仅解析 JSON 且仅查看请求头 Content-Type
与选项 type
匹配的中间件。该解析器接受任何 Unicode 编码的请求体,并支持自动解压 gzip
和 deflate
编码。
A new body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or undefined
if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.
中间件(即 req.body
)执行后,一个新的 body
对象会被填充到 request
对象中,其中包含解析后的数据;若无请求体可解析、 Content-Type
未匹配或发生错误,则填充 undefined
。
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
的结构基于用户控制的输入,该对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.body.foo.toString()
可能以多种方式失败: foo
可能不存在或非字符串类型,而 toString
可能不是函数而是字符串或其他用户输入。
The following table describes the properties of the optional options
object.
下表描述了可选对象 options
的属性。
Property 属性 | Description 描述 | Type 类型 | Default 默认值 |
---|---|---|---|
inflate |
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. 启用或禁用处理压缩(deflated)的请求体;禁用时,压缩的请求体会被拒绝。 |
Boolean 布尔值 | true |
limit |
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. 控制请求体的最大尺寸。若为数字,则该值指定字节数;若为字符串,则该值会被传递给字节库进行解析。 |
Mixed 混合类型 | "100kb" |
reviver |
The reviver option is passed directly to JSON.parse as the second argument. You can find more information on this argument in the MDN documentation about JSON.parse.reviver 选项直接作为第二个参数传递给 JSON.parse 。关于此参数的更多信息,可查阅 MDN 文档中有关 JSON.parse 的部分。 |
Function 函数 | null |
strict |
Enables or disables only accepting arrays and objects; when disabled will accept anything JSON.parse accepts.启用或禁用仅接受数组和对象;禁用时将接受 JSON.parse 所接受的任何内容。 |
Boolean 布尔值 | true |
type |
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like json ), a mime type (like application/json ), or a mime type with a wildcard (like */* or */json ). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.此选项用于确定中间件将解析的媒体类型。该选项可以是字符串、字符串数组或函数。若非函数, type 选项会直接传递给 type-is 库,可以是扩展名(如 json )、MIME 类型(如 application/json )或带通配符的 MIME 类型(如 */* 或 */json )。若为函数,则调用 type 选项为 fn(req) ,若返回真值则解析请求。 |
Mixed 混合 | "application/json" |
verify |
This option, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.如果提供此选项,它将被作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer , encoding 是请求的编码。通过抛出错误可以中止解析过程。 |
Function 函数 | undefined |
express.raw([options]) express.raw([选项])
This is a built-in middleware function in Express. It parses incoming request
payloads into a Buffer
and is based on
body-parser.
这是 Express 中的一个内置中间件函数。它将传入的请求负载解析为 Buffer
,并基于 body-parser。
Returns middleware that parses all bodies as a Buffer
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.
返回一个中间件,该中间件将所有请求体解析为 Buffer
,并且仅处理 Content-Type
请求头与 type
选项匹配的请求。此解析器接受任何 Unicode 编码的请求体,并支持自动解压 gzip
和 deflate
编码。
A new body
Buffer
containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or undefined
if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.
中间件执行后(即 req.body
),会在 request
对象上填充一个包含解析数据的新 body
Buffer
,如果没有可解析的请求体、 Content-Type
不匹配或发生错误,则填充 undefined
。
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.toString()
may fail in multiple ways, for example
stacking multiple parsers req.body
may be from a different parser. Testing
that req.body
is a Buffer
before calling buffer methods is recommended.
由于 req.body
的结构基于用户控制的输入,此对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.body.toString()
可能会以多种方式失败,比如堆叠多个解析器 req.body
可能来自不同的解析器。建议在调用 buffer 方法前验证 req.body
是否为 Buffer
。
The following table describes the properties of the optional options
object.
下表描述了可选 options
对象的属性。
Property 属性 | Description 描述 | Type 类型 | Default 默认 |
---|---|---|---|
inflate |
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. 启用或禁用处理压缩(deflated)的请求体;禁用时,压缩的请求体会被拒绝。 |
Boolean 布尔值 | true |
limit |
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. 控制请求体的最大尺寸。如果值为数字,则指定字节数;如果为字符串,该值会传递给 bytes 库进行解析。 |
Mixed 混合 | "100kb" |
type |
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like bin ), a mime type (like application/octet-stream ), or a mime type with a wildcard (like */* or application/* ). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.此选项用于确定中间件将解析的媒体类型。该选项可以是字符串、字符串数组或函数。若非函数, type 选项会直接传递给 type-is 库,可以是扩展名(如 bin )、MIME 类型(如 application/octet-stream )或带通配符的 MIME 类型(如 */* 或 application/* )。如果是函数, type 选项会作为 fn(req) 被调用,若返回真值则解析请求。 |
Mixed 混合 | "application/octet-stream" |
verify |
This option, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.若提供此选项,它将被作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer , encoding 是请求的编码。通过抛出错误可中止解析过程。 |
Function 函数 | undefined |
express.Router([options])
express.Router([选项])
Creates a new router object.
创建一个新的路由器对象。
const router = express.Router([options])
The optional options
parameter specifies the behavior of the router.
可选的 options
参数指定了路由器的行为。
Property 属性 | Description 描述 | Default 默认值 | Availability 可用性 |
---|---|---|---|
caseSensitive |
Enable case sensitivity. 启用大小写敏感。 |
Disabled by default, treating “/Foo” and “/foo” as the same. 默认禁用,将“/Foo”和“/foo”视为相同。 |
|
mergeParams |
Preserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.保留父路由器的 req.params 值。如果父级和子级有冲突的参数名,以子级值为准。 |
false |
4.5.0+ |
strict |
Enable strict routing. 启用严格路由。 | Disabled by default, “/foo” and “/foo/” are treated the same by the router. 默认情况下禁用,路由器会将“/foo”和“/foo/”视为相同路径。 |
You can add middleware and HTTP method routes (such as get
, put
, post
, and
so on) to router
just like an application.
你可以像应用程序一样,向 router
添加中间件和 HTTP 方法路由(例如 get
、 put
、 post
等)。
For more information, see Router.
更多信息,请参阅路由器文档。
express.static(root, [options])
This is a built-in middleware function in Express.
It serves static files and is based on serve-static.
这是 Express 中的一个内置中间件函数。它用于提供静态文件服务,基于 serve-static。
NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.
注意:为了达到最佳效果,建议使用反向代理缓存来提升静态资源服务的性能。
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.
参数 root
指定了提供静态资源的根目录。该函数通过将 req.url
与提供的 root
目录结合来确定要服务的文件。当文件未找到时,它不会发送 404 响应,而是调用 next()
以继续执行下一个中间件,从而实现堆叠和回退机制。
The following table describes the properties of the options
object.
See also the example below.
下表描述了 options
对象的属性。另请参阅下方的示例。
Property 属性 | Description 描述 | Type 类型 | Default 默认值 |
---|---|---|---|
dotfiles |
Determines how dotfiles (files or directories that begin with a dot “.”) are treated. 决定如何处理以点“.”开头的文件或目录(即点文件)。 See dotfiles below. 参见下方的点文件。 |
String 字符串 | “ignore” “忽略” |
etag |
Enable or disable etag generation 启用或禁用 etag 生成 NOTE: express.static always sends weak ETags.注意: express.static 总是发送弱 ETag。 |
Boolean 布尔值 | true |
extensions |
Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: ['html', 'htm'] .设置文件扩展名回退:如果未找到文件,则搜索具有指定扩展名的文件并返回找到的第一个。示例: ['html', 'htm'] 。 |
Mixed 混合类型 | false |
fallthrough |
Let client errors fall-through as unhandled requests, otherwise forward a client error. 让客户端错误穿透作为未处理的请求,否则转发客户端错误。 See fallthrough below. 参见下方的穿透设置。 |
Boolean 布尔值 | true |
immutable |
Enable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.启用或禁用响应头中的 immutable 指令。若启用,还应指定 maxAge 选项以启用缓存。 immutable 指令将阻止支持的客户端在 maxAge 选项的生命周期内发起条件请求来检查文件是否已更改。 |
Boolean 布尔值 | false |
index |
Sends the specified directory index file. Set to false to disable directory indexing.发送指定的目录索引文件。设置为 false 以禁用目录索引。 |
Mixed 混合 | “index.html” |
lastModified |
Set the Last-Modified header to the last modified date of the file on the OS.将 Last-Modified 头设置为操作系统上文件的最后修改日期。 |
Boolean 布尔值 | true |
maxAge |
Set the max-age property of the Cache-Control header in milliseconds or a string in ms format. 设置 Cache-Control 头部 max-age 属性的值,单位为毫秒或 ms 格式的字符串。 |
Number 数值 | 0 |
redirect |
Redirect to trailing “/” when the pathname is a directory. 当路径名指向目录时,重定向至末尾带“/”的路径。 |
Boolean 布尔值 | true |
setHeaders |
Function for setting HTTP headers to serve with the file. 用于设置 HTTP 头部以配合文件服务的函数。 See setHeaders below. 参见下方的 setHeaders。 |
Function 函数 |
For more information, see Serving static files in Express.
and Using middleware - Built-in middleware.
更多信息,请参阅 Express 中的静态文件服务和使用中间件 - 内置中间件。
dotfiles 点文件
Possible values for this option are:
此选项的可能值为:
- “allow” - No special treatment for dotfiles.
“allow” - 对点文件不做特殊处理。 - “deny” - Deny a request for a dotfile, respond with
403
, then callnext()
.
“deny” - 拒绝点文件请求,响应为403
,然后调用next()
。 - “ignore” - Act as if the dotfile does not exist, respond with
404
, then callnext()
.
“ignore” - 假装点文件不存在,响应为404
,然后调用next()
。
fallthrough
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
时,客户端错误如错误请求或请求不存在的文件将导致此中间件仅调用 next()
以触发堆栈中的下一个中间件。若为 false,这些错误(包括 404)将触发 next(err)
。
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.
将此选项设置为 true
,以便您可以将多个物理目录映射到相同的网络地址,或让路由填充不存在的文件。
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.
如果您已将此中间件挂载在严格设计为单一文件系统目录的路径上,请使用 false
,这样可以短路 404 错误以减少开销。此中间件还将响应所有方法。
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
, the response object.
res
,响应对象。path
, the file path that is being sent.
path
,正在发送的文件路径。stat
, thestat
object of the file that is being sent.
stat
,正在发送的文件的stat
对象。
Example of express.static
express.static 的示例
Here is an example of using the express.static
middleware function with an elaborate options object:
这里是一个使用 express.static
中间件函数配合详细选项对象的示例:
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.text([options]) express.text([选项])
This is a built-in middleware function in Express. It parses incoming request
payloads into a string and is based on
body-parser.
这是 Express 中的一个内置中间件函数。它将传入的请求负载解析为字符串,并基于 body-parser。
Returns middleware that parses all bodies as a string 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.
返回一个中间件,该中间件将所有请求体解析为字符串,并且仅处理 Content-Type
头部与 type
选项匹配的请求。此解析器接受任何 Unicode 编码的请求体,并支持自动解压 gzip
和 deflate
编码。
A new body
string containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or undefined
if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.
中间件处理后(即 req.body
),会在 request
对象上填充一个包含解析数据的新 body
字符串;如果没有可解析的请求体、 Content-Type
不匹配或发生错误,则为 undefined
。
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.trim()
may fail in multiple ways, for example
stacking multiple parsers req.body
may be from a different parser. Testing
that req.body
is a string before calling string methods is recommended.
由于 req.body
的结构基于用户控制的输入,该对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.body.trim()
可能会以多种方式失败,比如堆叠多个解析器 req.body
可能来自不同的解析器。建议在调用字符串方法前测试 req.body
是否为字符串。
The following table describes the properties of the optional options
object.
下表描述了可选 options
对象的属性。
Property 属性 | Description 描述 | Type 类型 | Default 默认 |
---|---|---|---|
defaultCharset |
Specify the default character set for the text content if the charset is not specified in the Content-Type header of the request.如果请求的 Content-Type 头部未指定字符集,则为此文本内容指定默认字符集。 |
String 字符串 | "utf-8" |
inflate |
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. 启用或禁用处理压缩(deflated)的请求体;禁用时,压缩的请求体会被拒绝。 |
Boolean 布尔值 | true |
limit |
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. 控制请求体的最大尺寸。若为数字,则该值指定字节数;若为字符串,该值会被传递给字节库进行解析。 |
Mixed 混合类型 | "100kb" |
type |
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like txt ), a mime type (like text/plain ), or a mime type with a wildcard (like */* or text/* ). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.此选项用于确定中间件将解析的媒体类型。可以是字符串、字符串数组或函数。若非函数, type 选项会直接传递给 type-is 库,可以是扩展名(如 txt )、MIME 类型(如 text/plain )或带通配符的 MIME 类型(如 */* 或 text/* )。若为函数, type 选项会作为 fn(req) 被调用,若返回真值则请求会被解析。 |
Mixed 混合 | "text/plain" |
verify |
This option, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.如果提供此选项,它将被调用为 verify(req, res, buf, encoding) ,其中 buf 是原始请求体的 Buffer ,而 encoding 是请求的编码。通过抛出错误可以中止解析过程。 |
Function 函数 | undefined |
express.urlencoded([options])
express.urlencoded([选项])
This is a built-in middleware function in Express. It parses incoming requests
with urlencoded payloads and is based on body-parser.
这是 Express 中的一个内置中间件函数。它解析带有 urlencoded 负载的传入请求,并基于 body-parser。
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.
返回一个仅解析 urlencoded 请求体且仅查看请求头 Content-Type
与选项 type
匹配的中间件。此解析器仅接受 UTF-8 编码的请求体,并支持自动解压 gzip
和 deflate
编码。
A new body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or undefined
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
),一个新的 body
对象包含解析后的数据会被填充到 request
对象上,若无请求体可解析、 Content-Type
未匹配或发生错误,则为 undefined
。此对象将包含键值对,其中值可以是字符串或数组(当 extended
为 false
时),或任意类型(当 extended
为 true
时)。
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
的结构基于用户控制的输入,该对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.body.foo.toString()
可能以多种方式失败,比如 foo
可能不存在或不是字符串,而 toString
可能不是函数而是字符串或其他用户输入。
The following table describes the properties of the optional options
object.
下表描述了可选 options
对象的属性。
Property 属性 | Description 描述 | Type 类型 | Default 默认 |
---|---|---|---|
extended |
This option allows to choose between parsing the URL-encoded data with the querystring library (when false ) or the qs library (when true ). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.此选项允许选择使用 querystring 库(当 false 时)或 qs 库(当 true 时)来解析 URL 编码的数据。“扩展”语法允许将丰富的对象和数组编码为 URL 编码格式,从而在使用 URL 编码时获得类似 JSON 的体验。更多信息,请参阅 qs 库。 |
Boolean 布尔值 | false |
inflate |
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. 启用或禁用处理压缩(deflated)的请求体;禁用时,压缩的请求体会被拒绝。 |
Boolean 布尔值 | true |
limit |
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. 控制请求体的最大尺寸。若为数字,则该值指定字节数;若为字符串,该值会被传递给字节库进行解析。 |
Mixed 混合类型 | "100kb" |
parameterLimit |
This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. 此选项控制 URL 编码数据中允许的最大参数数量。如果请求包含的参数超过此值,将引发错误。 |
Number 数字 | 1000 |
type |
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like urlencoded ), a mime type (like application/x-www-form-urlencoded ), or a mime type with a wildcard (like */x-www-form-urlencoded ). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.此选项用于确定中间件将解析的媒体类型。该选项可以是字符串、字符串数组或函数。若非函数, type 选项会直接传递给 type-is 库,可以是扩展名(如 urlencoded )、mime 类型(如 application/x-www-form-urlencoded )或带通配符的 mime 类型(如 */x-www-form-urlencoded )。若为函数, type 选项会作为 fn(req) 调用,若返回真值则请求会被解析。 |
Mixed 混合 | "application/x-www-form-urlencoded" |
verify |
This option, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.若提供此选项,它会被调用为 verify(req, res, buf, encoding) ,其中 buf 是原始请求体的 Buffer , encoding 是请求的编码。解析过程可通过抛出错误来中止。 |
Function 函数 | undefined |
Application 应用
The app
object conventionally denotes the Express application.
Create it by calling the top-level express()
function exported by the Express module:
通常, app
对象代表 Express 应用。通过调用 Express 模块导出的顶层 express()
函数来创建它:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
app.listen(3000)
The app
object has methods for
app
对象拥有以下方法用于
- Routing HTTP requests; see for example, app.METHOD and app.param.
路由 HTTP 请求;例如,参见 app.METHOD 和 app.param。 - Configuring middleware; see app.route.
配置中间件;参见 app.route。 - Rendering HTML views; see app.render.
渲染 HTML 视图;参见 app.render。 - Registering a template engine; see app.engine.
注册模板引擎;参见 app.engine。
It also has settings (properties) that affect how the application behaves;
for more information, see Application settings.
它还包含影响应用程序行为的设置(属性);更多信息,请参阅应用程序设置。
The Express application object can be referred from the request object and the response object as req.app
, and res.app
, respectively.
Express 应用程序对象可以通过请求对象和响应对象分别引用为 req.app
和 res.app
。
Properties 属性
app.locals
The app.locals
object has properties that are local variables within the application,
and will be available in templates rendered with res.render.
app.locals
对象拥有作为应用程序内局部变量的属性,这些属性将在使用 res.render 渲染的模板中可用。
The locals
object is used by view engines to render a response. The object
keys may be particularly sensitive and should not contain user-controlled
input, as it may affect the operation of the view engine or provide a path to
cross-site scripting. Consult the documentation for the used view engine for
additional considerations.
视图引擎使用 locals
对象来渲染响应。该对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的运行或提供跨站脚本攻击的途径。有关更多注意事项,请查阅所用视图引擎的文档。
console.dir(app.locals.title)
// => 'My App'
console.dir(app.locals.email)
// => 'me@myapp.com'
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.
一旦设置, app.locals
属性的值将在应用程序的整个生命周期中持续存在,这与仅在请求生命周期内有效的 res.locals 属性形成对比。
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)
您可以在应用程序内渲染的模板中访问局部变量。这对于向模板提供辅助函数以及应用级数据非常有用。局部变量可通过 req.app.locals
在中间件中访问(参见 req.app)。
app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = 'me@myapp.com'
app.mountpath
The app.mountpath
property contains one or more path patterns on which a sub-app was mounted.
app.mountpath
属性包含一个或多个子应用挂载的路径模式。
A sub-app is an instance of express
that may be used for handling the request to a route.
子应用是 express
的一个实例,可用于处理对某一路由的请求。
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
It is similar to the baseUrl property of the req
object, except req.baseUrl
returns the matched URL path, instead of the matched patterns.
这与 req
对象的 baseUrl 属性类似,不同之处在于 req.baseUrl
返回的是匹配的 URL 路径,而非匹配的模式。
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.
如果一个子应用挂载在多个路径模式上, app.mountpath
会返回其挂载的所有模式列表,如下例所示。
const admin = express()
admin.get('/', (req, res) => {
console.log(admin.mountpath) // [ '/adm{*splat}n', '/manager' ]
res.send('Admin Homepage')
})
const secret = express()
secret.get('/', (req, res) => {
console.log(secret.mountpath) // /secr{*splat}t
res.send('Admin Secret')
})
admin.use('/secr{*splat}t', secret) // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app
app.use(['/adm{*splat}n', '/manager'], admin) // load the 'admin' router on '/adm{*splat}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)
You can add middleware and HTTP method routes to the router
just like an application.
您可以像对待应用程序一样,向 router
添加中间件和 HTTP 方法路由。
For more information, see Router.
更多信息,请参阅 Router。
Events 事件
app.on('mount', callback(parent))
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.
当子应用挂载到父应用上时,会触发 mount
事件。父应用会被传递给回调函数。
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)
Methods 方法
app.all(path, callback [, callback ...])
This method is like the standard app.METHOD() methods,
except it matches all HTTP verbs.
此方法与标准的 app.METHOD() 方法类似,但它匹配所有的 HTTP 动词。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认值 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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 示例
The following callback is executed for requests to /secret
whether using
GET, POST, PUT, DELETE, or any other HTTP request method:
无论使用 GET、POST、PUT、DELETE 还是其他任何 HTTP 请求方法,以下回调都会针对 /secret
的请求执行:
app.all('/secret', (req, res, next) => {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
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()
方法对于为特定路径前缀或任意匹配映射“全局”逻辑非常有用。例如,如果你在所有其他路由定义的最前面放置以下代码,它将要求从该点开始的所有路由都需要认证,并自动加载用户。请记住,这些回调不必作为端点: loadUser
可以执行一个任务,然后调用 next()
以继续匹配后续路由。
app.all('{*splat}', requireAuthentication, loadUser)
Or the equivalent: 或等效于:
app.all('{*splat}', requireAuthentication)
app.all('{*splat}', loadUser)
Another example is white-listed “global” functionality.
The example is similar to the ones above, but it only restricts paths that start with
“/api”:
另一个例子是白名单中的“全局”功能。此示例与上述类似,但仅限制以“/api”开头的路径:
app.all('/api/{*splat}', requireAuthentication)
app.delete(path, callback [, callback ...])
Routes HTTP DELETE requests to the specified path with the specified callback functions.
For more information, see the routing guide.
将 HTTP DELETE 请求路由到指定路径,并使用指定的回调函数。更多信息,请参阅路由指南。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认值 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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)
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')
.
将布尔设置 name
设为 false
,其中 name
是应用设置表中的属性之一。对布尔属性调用 app.set('foo', false)
等同于调用 app.disable('foo')
。
For example: 例如:
app.disable('trust proxy')
app.get('trust proxy')
// => false
app.disabled(name)
Returns true
if the Boolean setting name
is disabled (false
), where name
is one of the properties from
the app settings table.
如果布尔设置 name
被禁用( false
),则返回 true
,其中 name
是应用设置表中的属性之一。
app.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false
app.enable(name)
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')
.
将布尔设置 name
设为 true
,其中 name
是应用设置表中的属性之一。对布尔属性调用 app.set('foo', true)
等同于调用 app.enable('foo')
。
app.enable('trust proxy')
app.get('trust proxy')
// => true
app.enabled(name)
Returns true
if the setting name
is enabled (true
), where name
is one of the
properties from the app settings table.
如果设置 name
已启用( true
),则返回 true
,其中 name
是应用设置表中的属性之一。
app.enabled('trust proxy')
// => false
app.enable('trust proxy')
app.enabled('trust proxy')
// => true
app.engine(ext, callback)
Registers the given template engine callback
as ext
.
将给定的模板引擎 callback
注册为 ext
。
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.
默认情况下,Express 会根据文件扩展名 require()
引擎。例如,若尝试渲染“foo.pug”文件,Express 内部会调用以下内容,并在后续调用中缓存 require()
以提高性能。
app.engine('pug', require('pug').__express)
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.
对于不提供开箱即用 .__express
的引擎,或希望将不同扩展名“映射”到模板引擎时,可使用此方法。
For example, to map the EJS template engine to “.html” files:
例如,将 EJS 模板引擎映射到“.html”文件:
app.engine('html', require('ejs').renderFile)
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.
在此情况下,EJS 提供了一个与 Express 预期签名相同的 .renderFile()
方法: (path, options, callback)
,但请注意,它在内部将此方法别名为 ejs.__express
,因此若使用“.ejs”扩展名则无需额外操作。
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.
部分模板引擎并不遵循这一惯例。consolidate.js 库将 Node 模板引擎映射为遵循此惯例,以便它们能与 Express 无缝协作。
const engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
app.get(name)
Returns the value of name
app setting, where name
is one of the strings in the
app settings table. For example:
返回@app 设置的值,其中 name
是应用设置表中的字符串之一。例如:
app.get('title')
// => undefined
app.set('title', 'My Site')
app.get('title')
// => "My Site"
app.get(path, callback [, callback ...])
Routes HTTP GET requests to the specified path with the specified callback functions.
将 HTTP GET 请求路由到指定路径,并执行相应的回调函数。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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])
Starts a UNIX socket and listens for connections on the given path.
This method is identical to Node’s http.Server.listen().
启动一个 UNIX 套接字并在指定路径上监听连接。此方法与 Node 的 http.Server.listen()相同。
const express = require('express')
const app = express()
app.listen('/tmp/sock')
app.listen([port[, host[, backlog]]][, callback])
app.listen([端口[, 主机[, 积压数]]][, 回调函数])
Binds and listens for connections on the specified host and port.
This method is identical to Node’s http.Server.listen().
在指定的主机和端口上绑定并监听连接。此方法与 Node 的 http.Server.listen()相同。
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.).
如果省略端口或设为 0,操作系统将分配任意一个未使用的端口,这对于自动化任务(如测试等)场景非常有用。
const express = require('express')
const app = express()
app.listen(3000)
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):
express()
返回的 app
实际上是一个 JavaScript Function
,设计用于作为回调传递给 Node 的 HTTP 服务器以处理请求。这使得用相同的代码库提供 HTTP 和 HTTPS 版本的应用程序变得容易,因为应用程序并不继承这些(它只是一个回调):
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)
The app.listen()
method returns an http.Server object and (for HTTP) is a convenience method for the following:
app.listen()
方法返回一个 http.Server 对象,并且(对于 HTTP)是以下操作的便捷方法:
app.listen = function () {
const server = http.createServer(this)
return server.listen.apply(server, arguments)
}
Note 注意
All the forms of Node’s http.Server.listen() method are in fact actually supported.
实际上,Node 的 http.Server.listen()方法的所有形式都是被支持的。
app.METHOD(path, callback [, callback ...])
app.METHOD(路径, 回调函数 [, 回调函数 ...])
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.
路由一个 HTTP 请求,其中 METHOD 是该请求的 HTTP 方法,如 GET、PUT、POST 等,均为小写。因此,实际的方法包括 app.get()
、 app.post()
、 app.put()
等。完整列表请参见下方的路由方法。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
有关示例,请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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 supports the following routing methods corresponding to the HTTP methods of the same names:
Express 支持以下路由方法,对应同名的 HTTP 方法:
|
|
|
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.
API 文档仅明确记录了最流行的 HTTP 方法 app.get()
、 app.post()
、 app.put()
和 app.delete()
。然而,上面列出的其他方法以完全相同的方式工作。
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ...
.
要路由那些转换为无效 JavaScript 变量名的方法,请使用括号表示法。例如, app['m-search']('/', function ...
。
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.get()
之前未对路径调用 app.head()
,则 app.get()
函数除了 GET
方法外,还会自动为 HTTP HEAD
方法调用。
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.
方法 app.all()
并非源自任何 HTTP 方法,它会为所有 HTTP 请求方法在指定路径加载中间件。更多信息,请参阅 app.all。
For more information on routing, see the routing guide.
有关路由的更多信息,请参阅路由指南。
app.param(name, callback)
app.param(名称, 回调函数)
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
是回调函数。回调函数的参数依次为请求对象、响应对象、下一个中间件、参数值及参数名称。
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.
如果 name
是一个数组,那么 callback
触发器会按照声明的顺序为其中每个参数注册。此外,对于除最后一个参数外的每个声明参数,回调内部调用 next
将会触发下一个声明参数的回调。对于最后一个参数,调用 next
则会调用当前处理路由的下一个中间件,就像 name
仅是一个字符串时那样。
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.
例如,当路由路径中存在 :user
时,你可以将用户加载逻辑映射到该路由,自动提供 req.user
,或对参数输入执行验证。
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'))
}
})
})
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on app
will be triggered only by route parameters defined on app
routes.
参数回调函数的作用域仅限于定义它们的路由器。它们不会被挂载的应用或路由器继承,也不会因从父路由器继承的路由参数而触发。因此,在 app
上定义的参数回调仅由 app
路由上定义的路由参数触发。
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()
})
On GET /user/42
, the following is printed:
在 GET /user/42
上,将打印以下内容:
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()
})
On GET /user/42/3
, the following is printed:
在 GET /user/42/3
上,将打印以下内容:
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'
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.
在挂载应用的复杂场景中,此方法的行为可能变得非常复杂:通常更推荐使用 req.baseUrl 来获取应用的标准路径。
app.post(path, callback [, callback ...])
app.post(路径, 回调函数 [, 回调函数 ...])
Routes HTTP POST requests to the specified path with the specified callback functions.
For more information, see the routing guide.
将 HTTP POST 请求路由到指定路径,并执行相应的回调函数。更多信息,请参阅路由指南。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认值 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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 ...])
Routes HTTP PUT requests to the specified path with the specified callback functions.
将 HTTP PUT 请求路由到指定路径,并使用指定的回调函数处理。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认值 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可以是:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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)
app.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.
通过 callback
函数返回视图渲染后的 HTML。它接受一个可选参数,该参数是一个包含视图局部变量的对象。类似于 res.render(),但它无法自行将渲染后的视图发送给客户端。
Think of app.render()
as a utility function for generating rendered view strings.
Internally res.render()
uses app.render()
to render views.
可以将 app.render()
视为生成渲染视图字符串的实用函数。在内部, res.render()
使用 app.render()
来渲染视图。
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.
view
参数执行文件系统操作,如从磁盘读取文件和评估 Node.js 模块,出于安全考虑,不应包含来自最终用户的输入。
The locals
object is used by view engines to render a response. The object
keys may be particularly sensitive and should not contain user-controlled
input, as it may affect the operation of the view engine or provide a path to
cross-site scripting. Consult the documentation for the used view engine for
additional considerations.
locals
对象被视图引擎用于渲染响应。该对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的操作或提供跨站脚本的途径。请查阅所用视图引擎的文档以获取更多注意事项。
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.
局部变量 cache
保留用于启用视图缓存。在开发期间若需缓存视图,请将其设置为 true
;生产环境下默认启用视图缓存。
app.render('email', (err, html) => {
// ...
})
app.render('email', { name: 'Tobi' }, (err, html) => {
// ...
})
app.route(path) 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).
返回单个路由的实例,随后可用于通过可选中间件处理 HTTP 动词。使用 app.route()
以避免重复的路由名称(从而避免拼写错误)。
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) app.set(名称, 值)
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.
将设置 name
赋值为 value
。您可以存储任何所需的值,但某些名称可用于配置服务器的行为。这些特殊名称列在应用设置表中。
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.set('foo', true)
等同于调用 app.enable('foo')
。类似地,对布尔属性调用 app.set('foo', false)
等同于调用 app.disable('foo')
。
Retrieve the value of a setting with app.get()
.
使用 app.get()
获取设置的值。
app.set('title', 'My Site')
app.get('title') // "My Site"
Application Settings 应用程序设置
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.
继承无默认值的设置项值;这些在下方表格中有明确标注。
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”).
例外情况:子应用将继承 trust proxy
的值,尽管它有默认值(为了向后兼容);在生产环境中(当 NODE_ENV
为“production”时),子应用不会继承 view cache
的值。
Property 属性 | Type 类型 | Description 描述 | Default 默认值 |
---|---|---|---|
|
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) 不适用(未定义) |
|
String 字符串 | Environment mode.
Be sure to set to "production" in a production environment;
see Production best practices: performance and reliability.
环境模式。请确保在生产环境中设置为“production”;参见生产环境最佳实践:性能与可靠性。 |
|
|
Varied 多样化 |
Set the ETag response header. For possible values, see the More about the HTTP ETag header. |
|
|
String 字符串 | Specifies the default JSONP callback name. 指定默认的 JSONP 回调名称。 |
“callback” |
|
Boolean 布尔值 |
Enable escaping JSON responses from the NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) 不适用(未定义) |
|
Varied 多样化的 | The 'replacer' argument used by `JSON.stringify`.
`JSON.stringify`所使用的'replacer'参数。 NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) 不适用(未定义) |
|
Varied 多样化的 | The 'space' argument used by `JSON.stringify`.
This is typically set to the number of spaces to use to indent prettified JSON.
`JSON.stringify`使用的'space'参数。通常设置为用于缩进美化 JSON 的空格数。 NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) 不适用(未定义) |
|
Varied 多样化 |
Disable query parsing by setting the value to The simple query parser is based on Node’s native query parser, querystring. 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. |
"simple" ""simple" " |
|
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) 不适用(未定义) |
|
Number 数字 | The number of dot-separated parts of the host to remove to access subdomain. 访问子域名需要移除的主机名中以点分隔的部分数量。 |
2 |
|
Varied 多样化的 |
Indicates the app is behind a front-facing proxy, and to use the
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.
|
|
|
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. 应用程序视图的目录或目录数组。如果是数组,则按数组中出现的顺序查找视图。 |
|
|
Boolean 布尔值 | Enables view template compilation caching. NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production"). |
|
|
String 字符串 | The default engine extension to use when omitted.
省略时使用的默认引擎扩展。 NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) 不适用(未定义) |
|
Boolean 布尔值 | Enables the "X-Powered-By: Express" HTTP header. 启用 'X-Powered-By: Express' HTTP 头部。 |
|
Options for `trust proxy` setting
`trust proxy` 设置的选项
Read Express behind proxies for more
information.
阅读 Express 在代理后的配置以获取更多信息。
Type 类型 | Value 值 |
---|---|
Boolean 布尔值 |
If If |
String 字符串 String containing comma-separated values 包含逗号分隔值的字符串 Array of strings 字符串数组 |
An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:
Set IP addresses in any of the following ways: Specify a single subnet:
Specify a subnet and an address:
Specify multiple subnets as CSV:
Specify multiple subnets as an array:
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 数字 |
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.
|
Options for `etag` setting
`etag` 设置的选项
NOTE: These settings apply only to dynamic files, not static files.
The express.static middleware ignores these settings.
注意:这些设置仅适用于动态文件,不适用于静态文件。express.static 中间件会忽略这些设置。
The ETag functionality is implemented using the
etag package.
For more information, see its documentation.
ETag 功能是通过 etag 包实现的。更多信息,请参阅其文档。
Type 类型 | Value 值 |
---|---|
Boolean 布尔值 |
|
String 字符串 |
If "strong", enables strong ETag. 若设为“strong”,则启用强 ETag。 If "weak", enables weak ETag. 若设为“weak”,则启用弱 ETag。 |
Function 函数 |
Custom ETag function implementation. Use this only if you know what you are doing.
|
app.use([path,] callback [, callback...])
app.use([路径,] 回调函数 [, 回调函数...])
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
.
将指定的中间件函数或函数组挂载到指定路径:当请求路径的基址匹配 path
时,执行该中间件函数。
Arguments 参数
Argument 参数 | Description 描述 | Default 默认 |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
调用中间件函数的路径;可以是以下任意一种:
示例请参见路径示例。 |
'/' (root path) '/'(根路径) |
callback |
Callback functions; can be:
回调函数;可选值包括:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke
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 描述
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.
一个路由会匹配任何紧随其路径后带有“ /
”的路径。例如: app.use('/apple', ...)
将匹配“/apple”、“/apple/images”、“/apple/images/news”等。
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:
由于 path
默认为“/”,未指定路径挂载的中间件将对应用的每个请求执行。例如,以下中间件函数将对应用的每个请求执行:
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
错误处理中间件
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.
错误处理中间件始终需要四个参数。必须提供四个参数以将其识别为错误处理中间件函数。即使不需要使用 next
对象,也必须指定它以保持签名一致。否则, next
对象将被解释为常规中间件,从而无法处理错误。有关错误处理中间件的详细信息,请参阅:错误处理。
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)
):
定义错误处理中间件函数的方式与其他中间件函数相同,但需使用四个参数而非三个,具体签名为 (err, req, res, next)
):
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Path examples 路径示例
The following table provides some simple examples of valid path
values for
mounting middleware.
下表提供了一些有效的 path
值用于挂载中间件的简单示例。
Type 类型 | Example 示例 |
---|---|
Path 路径 |
This will match paths starting with
|
Path Pattern 路径模式 |
This will match paths starting with
|
Regular Expression 正则表达式 |
This will match paths starting with
|
Array 数组 |
This will match paths starting with
|
Middleware callback function examples
中间件回调函数示例
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()
.
下表提供了一些简单的中间件函数示例,这些函数可用作 callback
参数传递给 app.use()
、 app.METHOD()
和 app.all()
。
Usage 用法 | Example 示例 |
---|---|
Single Middleware 单一中间件 |
You can define and mount a middleware function locally.
A router is valid middleware.
An Express app is valid middleware.
|
Series of Middleware 中间件系列 |
You can specify more than one middleware function at the same mount path.
|
Array 数组 |
Use an array to group middleware logically.
|
Combination 组合 |
You can combine all the above ways of mounting middleware.
|
Following are some examples of using the express.static
middleware in an Express app.
以下是 Express 应用中使用 express.static 中间件的一些示例。
Serve static content for the app from the “public” directory in the application directory:
从应用程序目录中的“public”文件夹提供静态内容服务:
// GET /style.css etc
app.use(express.static(path.join(__dirname, 'public')))
Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:
将中间件挂载到“/static”路径,仅当请求路径以“/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())
Serve static files from multiple directories, but give precedence to “./public” over the others:
从多个目录提供静态文件,但优先使用“./public”而非其他目录:
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))
Request 请求
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.
req
对象代表 HTTP 请求,并包含请求查询字符串、参数、请求体、HTTP 标头等属性。在本文档及约定中,该对象始终被称为 req
(HTTP 响应则为 res
),但其实际名称由您所操作的回调函数参数决定。
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}`)
})
The req
object is an enhanced version of Node’s own request object
and supports all built-in fields and methods.
req
对象是 Node 自身请求对象的增强版本,支持所有内置字段和方法。
Properties 属性
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.
在 Express 4 中,默认情况下 req.files
不再在 req
对象上可用。要访问 req.files
对象上的上传文件,请使用如 busboy、multer、formidable、multiparty、connect-multiparty 或 pez 等多部分处理中间件。
req.app
This property holds a reference to the instance of the Express application that is using the middleware.
此属性持有对正在使用该中间件的 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
如果你遵循创建一个仅导出中间件函数的模块并在主文件中 require()
它的模式,那么中间件可以通过 req.app
访问 Express 实例
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
The URL path on which a router instance was mounted.
路由器实例被挂载的 URL 路径。
The req.baseUrl
property is similar to the mountpath property of the app
object,
except app.mountpath
returns the matched path pattern(s).
req.baseUrl
属性类似于 app
对象的 mountpath 属性,不同之处在于 app.mountpath
返回匹配的路径模式。
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'
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.
即使您使用路径模式或一组路径模式来加载路由器, baseUrl
属性返回的是匹配的字符串,而非模式本身。在以下示例中, greet
路由器是基于两个路径模式加载的。
app.use(['/gre:"param"t', '/hel{l}o'], greet) // load the router on '/gre:"param"t' and '/hel{l}o'
When a request is made to /greet/jp
, req.baseUrl
is “/greet”. When a request is
made to /hello/jp
, req.baseUrl
is “/hello”.
当请求发送至 /greet/jp
时, req.baseUrl
为“/greet”。当请求发送至 /hello/jp
时, req.baseUrl
为“/hello”。
req.body
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 express.json()
or express.urlencoded()
.
包含请求体中提交的数据键值对。默认情况下为 undefined
,当使用如 express.json()
或 express.urlencoded()
这类请求体解析中间件时会被填充。
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
的结构基于用户控制的输入,该对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.body.foo.toString()
可能以多种方式失败,比如 foo
可能不存在或不是字符串,而 toString
可能不是函数而是字符串或其他用户输入。
The following example shows how to use body-parsing middleware to populate req.body
.
以下示例展示了如何使用请求体解析中间件来填充 req.body
。
const express = require('express')
const app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', (req, res, next) => {
console.log(req.body)
res.json(req.body)
})
req.cookies
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-parser 中间件时,该属性是一个包含请求发送的 cookie 的对象。如果请求不包含任何 cookie,则默认为 {}
。
// Cookie: name=tj
console.dir(req.cookies.name)
// => "tj"
If the cookie has been signed, you have to use req.signedCookies.
如果 cookie 已被签名,你必须使用 req.signedCookies。
For more information, issues, or concerns, see cookie-parser.
如需更多信息、问题或疑虑,请参阅 cookie-parser。
req.fresh 请求新鲜
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.
当响应在客户端缓存中仍为“新鲜”时,返回 true
,否则返回 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.
当客户端发送 Cache-Control: no-cache
请求头以表示端到端重载请求时,此模块将返回 false
,使处理这些请求变得透明。
Further details for how cache validation works can be found in the
HTTP/1.1 Caching Specification.
有关缓存验证如何工作的更多详情,请参阅 HTTP/1.1 缓存规范。
console.dir(req.fresh)
// => true
req.host
Contains the host derived from the Host
HTTP header.
包含从 Host
HTTP 头部派生的主机信息。
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.
当 trust proxy
设置未评估为 false
时,此属性将转而从 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.
如果请求中存在多个 X-Forwarded-Host
头部,则使用第一个头部的值。这包括带有逗号分隔值的单个头部,此时将使用第一个值。
// Host: "example.com:3000"
console.dir(req.host)
// => 'example.com:3000'
// Host: "[::1]:3000"
console.dir(req.host)
// => '[::1]:3000'
req.hostname
Contains the hostname derived from the Host
HTTP header.
包含从 Host
HTTP 头部派生的主机名。
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.
当 trust proxy
设置未评估为 false
时,此属性将转而从 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.
如果请求中存在多个 X-Forwarded-Host
头部,则使用第一个头部的值。这包括带有逗号分隔值的单个头部,此时将使用第一个值。
Prior to Express v4.17.0, the X-Forwarded-Host
could not contain multiple
values or be present more than once.
在 Express v4.17.0 之前, X-Forwarded-Host
不能包含多个值或多次出现。
// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'
req.ip 请求的 IP 地址
Contains the remote IP address of the request.
包含请求的远程 IP 地址。
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.
当 trust proxy
设置未评估为 false
时,此属性的值来源于 X-Forwarded-For
标头中最左侧的条目。该标头可由客户端或代理设置。
console.dir(req.ip)
// => "127.0.0.1"
req.ips
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.
当 trust proxy
设置未评估为 false
时,此属性包含 X-Forwarded-For
请求标头中指定的 IP 地址数组。否则,它将包含一个空数组。该标头可由客户端或代理设置。
For example, if X-Forwarded-For
is client, proxy1, proxy2
, req.ips
would be
["client", "proxy1", "proxy2"]
, where proxy2
is the furthest downstream.
例如,如果 X-Forwarded-For
是 client, proxy1, proxy2
, req.ips
将是 ["client", "proxy1", "proxy2"]
,其中 proxy2
位于最下游。
req.method
Contains a string corresponding to the HTTP method of the request:
GET
, POST
, PUT
, and so on.
包含一个字符串,对应请求的 HTTP 方法: GET
、 POST
、 PUT
等。
req.originalUrl
req.url
is not a native Express property, it is inherited from Node’s http module.
req.url
不是 Express 的原生属性,它继承自 Node 的 http 模块。
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.
此属性与 req.url
非常相似;然而,它保留了原始请求 URL,允许您自由重写 req.url
以用于内部路由目的。例如,app.use()的“挂载”功能会重写 req.url
以去除挂载点。
// GET /search?q=something
console.dir(req.originalUrl)
// => "/search?q=something"
req.originalUrl
is available both in middleware and router objects, and is a
combination of req.baseUrl
and req.url
. Consider following example:
req.originalUrl
在中间件和路由器对象中均可使用,它是 req.baseUrl
和 req.url
的组合。请看以下示例:
// 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
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 {}
.
此属性是一个对象,包含映射到命名路由“参数”的属性。例如,如果您有路由 /user/:name
,那么“name”属性可作为 req.params.name
使用。此对象默认为 {}
。
// GET /user/tj
console.dir(req.params.name)
// => "tj"
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.
当你在路由定义中使用正则表达式时,捕获组会以数组形式提供,其中 req.params[n]
表示第 n th 个捕获组, n
代表该捕获组。
app.use(/^\/file\/(.*)$/, (req, res) => {
// GET /file/javascripts/jquery.js
console.dir(req.params[0])
// => "javascripts/jquery.js"
})
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
中的键,请使用 app.param 处理器。更改仅适用于路由路径中已定义的参数。
Any changes made to the req.params
object in a middleware or route handler will be reset.
对中间件或路由处理程序中的 req.params
对象所做的任何更改都将被重置。
Note 注意
Express automatically decodes the values in req.params
(using decodeURIComponent
).
Express 自动解码 req.params
中的值(使用 decodeURIComponent
)。
req.path
Contains the path part of the request URL.
包含请求 URL 的路径部分。
// example.com/users?sort=desc
console.dir(req.path)
// => "/users"
When called from a middleware, the mount point is not included in req.path
. See app.use() for more details.
当从中间件调用时,挂载点不包含在 req.path
中。更多详情请参阅 app.use()。
req.protocol
Contains the request protocol string: either http
or (for TLS requests) https
.
包含请求协议字符串:可能是 http
或(对于 TLS 请求) https
。
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.
当 trust proxy
设置未评估为 false
时,此属性将使用 X-Forwarded-Proto
头字段的值(如果存在)。此头部可由客户端或代理设置。
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.
该属性是一个对象,包含路由中每个查询字符串参数对应的属性。当查询解析器设置为禁用时,它是一个空对象 {}
,否则它是配置的查询解析器的结果。
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.
由于 req.query
的结构基于用户控制的输入,该对象中的所有属性和值均不可信,应在信任前进行验证。例如, req.query.foo.toString()
可能以多种方式失败,比如 foo
可能不存在或不是字符串,而 toString
可能不是函数而是字符串或其他用户输入。
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
:
此属性的值可通过查询解析器应用程序设置进行配置,以适应应用程序的需求。一个非常流行的查询字符串解析器是 qs
模块,默认情况下即使用此模块。 qs
模块具有高度可配置性,提供多种设置选项,有时可能需要采用不同于默认值的设置来填充 req.query
。
const qs = require('qs')
app.set('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.dir(req.route, { depth: null })
res.send('GET')
})
Example output from the previous snippet:
上一个代码片段的示例输出:
Route {
path: '/user/{:id}',
stack: [
Layer {
handle: [Function (anonymous)],
keys: [],
name: '<anonymous>',
params: undefined,
path: undefined,
slash: false,
matchers: [ [Function: match] ],
method: 'get'
}
],
methods: [Object: null prototype] { get: true }
}
req.secure
A Boolean property that is true if a TLS connection is established. Equivalent to the following:
一个布尔属性,若 TLS 连接已建立则为真。等价于以下内容:
req.protocol === 'https'
req.signedCookies
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-parser 中间件时,此属性包含请求发送的已签名 cookie,这些 cookie 未经签名且可供直接使用。已签名的 cookie 存放在另一个对象中以表明开发者意图;否则,恶意攻击可能会针对 req.cookie
值(这些值易于伪造)发起。请注意,对 cookie 进行签名并不会使其“隐藏”或加密;而仅仅是防止篡改(因为用于签名的密钥是私有的)。
If no signed cookies are sent, the property defaults to {}
.
如果没有发送已签名的 cookie,该属性默认为 {}
。
// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
console.dir(req.signedCookies.user)
// => "tobi"
For more information, issues, or concerns, see cookie-parser.
如需更多信息、问题或疑虑,请参阅 cookie-parser。
req.stale
Indicates whether the request is “stale,” and is the opposite of req.fresh
.
For more information, see req.fresh.
指示请求是否为“陈旧”的,与 req.fresh
相反。更多信息,请参阅 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"]
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.
应用程序属性 subdomain offset
(默认值为 2)用于确定子域段的起始位置。若要更改此行为,请使用 app.set 修改其值。
req.xhr
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.
一个布尔属性,当请求的 X-Requested-With
头字段为“XMLHttpRequest”时值为 true
,表示该请求由如 jQuery 等客户端库发起。
console.dir(req.xhr)
// => true
Methods 方法
req.accepts(types)
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"
).
检查指定的内容类型是否可接受,基于请求的 Accept
HTTP 头字段。该方法返回最佳匹配,如果没有任何指定的内容类型可接受,则返回 false
(这种情况下,应用程序应响应 406 "Not Acceptable"
)。
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).
type
值可以是单个 MIME 类型字符串(如“application/json”)、扩展名(如“json”)、逗号分隔的列表或数组。对于列表或数组,该方法返回最佳匹配(如果有)。
// 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"
For more information, or if you have issues or concerns, see accepts.
如需更多信息,或遇到问题与疑虑,请参阅 accepts。
req.acceptsCharsets(charset [, ...])
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
.
根据请求的 Accept-Charset
HTTP 头字段,返回指定字符集中第一个被接受的字符集。如果指定的字符集均未被接受,则返回 false
。
For more information, or if you have issues or concerns, see accepts.
如需更多信息,或遇到问题及疑虑,请参阅 accepts。
req.acceptsEncodings(encoding [, ...])
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
.
根据请求的 Accept-Encoding
HTTP 头部字段,返回指定编码中第一个被接受的编码。如果所有指定编码均未被接受,则返回 false
。
For more information, or if you have issues or concerns, see accepts.
如需更多信息,或遇到问题及疑虑,请参阅 accepts。
req.acceptsLanguages([lang, ...])
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
.
根据请求的 Accept-Language
HTTP 头部字段,返回指定语言中第一个被接受的语言。如果所有指定语言均未被接受,则返回 false
。
If no lang
argument is given, then req.acceptsLanguages()
returns all languages from the HTTP Accept-Language
header
as an Array
.
如果未提供 lang
参数,则 req.acceptsLanguages()
会将 HTTP Accept-Language
头中的所有语言作为 Array
返回。
For more information, or if you have issues or concerns, see accepts.
如需更多信息,或遇到问题及疑虑,请参阅 accepts。
Express (5.x) source: request.js line 172
Express (5.x) 源码:request.js 第 172 行
Accepts (2.0) source: index.js line 195
Accepts (2.0) 源码:index.js 第 195 行
req.get(field)
Returns the specified HTTP request header field (case-insensitive match).
The Referrer
and Referer
fields are interchangeable.
返回指定的 HTTP 请求头字段(不区分大小写匹配)。 Referrer
和 Referer
字段可互换使用。
req.get('Content-Type')
// => "text/plain"
req.get('content-type')
// => "text/plain"
req.get('Something')
// => undefined
Aliased as req.header(field)
. 别名为 req.header(field)
。
req.is(type)
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.
如果传入请求的“Content-Type”HTTP 头字段与 type
参数指定的 MIME 类型匹配,则返回匹配的内容类型。如果请求没有正文,返回 null
。否则返回 false
。
// 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
For more information, or if you have issues or concerns, see type-is.
欲了解更多信息,或遇到问题与疑虑,请参阅 type-is。
req.range(size[, options])
Range
header parser. Range
头部解析器。
The size
parameter is the maximum size of the resource.
size
参数表示资源的最大大小。
The options
parameter is an object that can have the following properties.
options
参数是一个对象,可以包含以下属性。
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.指定是否应合并重叠及相邻的范围,默认为 false 。当设为 true 时,范围将被合并并返回,如同它们在头部以这种方式指定一样。 |
An array of ranges will be returned or negative numbers indicating an error parsing.
将返回一个范围数组或表示解析错误的负数。
-2
signals a malformed header string
-2
表示头部字符串格式错误-1
signals an unsatisfiable range
-1
表示无法满足的范围
// 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
})
}
Response 响应
The res
object represents the HTTP response that an Express app sends when it gets an HTTP request.
res
对象代表 Express 应用在接收到 HTTP 请求时发送的 HTTP 响应。
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.
在本文档及约定俗成的用法中,该对象始终被称为 res
(而 HTTP 请求则称为 req
),但其实际名称由您当前工作的回调函数参数决定。
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}`)
})
The res
object is an enhanced version of Node’s own response object
and supports all built-in fields and methods.
res
对象是 Node 自身响应对象的增强版本,支持所有内置字段和方法。
Properties 属性
res.app
This property holds a reference to the instance of the Express application that is using the middleware.
此属性持有对正在使用该中间件的 Express 应用程序实例的引用。
res.app
is identical to the req.app property in the request object.
res.app
与请求对象中的 req.app 属性相同。
res.headersSent
Boolean property that indicates if the app sent HTTP headers for the response.
布尔属性,指示应用是否已发送响应的 HTTP 头部。
app.get('/', (req, res) => {
console.log(res.headersSent) // false
res.send('OK')
console.log(res.headersSent) // true
})
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.
使用此属性设置可通过 res.render 渲染的模板中访问的变量。在 res.locals
上设置的变量仅在单个请求-响应周期内可用,不会在请求之间共享。
The locals
object is used by view engines to render a response. The object
keys may be particularly sensitive and should not contain user-controlled
input, as it may affect the operation of the view engine or provide a path to
cross-site scripting. Consult the documentation for the used view engine for
additional considerations.
locals
对象被视图引擎用于渲染响应。该对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的操作或提供跨站脚本的途径。请查阅所用视图引擎的文档以获取更多注意事项。
In order to keep local variables for use in template rendering between requests, use
app.locals instead.
为了在请求之间保留局部变量以供模板渲染使用,请改用 app.locals。
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.
此属性持有与当前响应对象相关联的请求对象的引用。
Methods 方法
res.append(field [, value])
res.append()
is supported by Express v4.11.0+
res.append()
由 Express v4.11.0+ 支持
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.
将指定的 value
追加到 HTTP 响应头 field
中。如果该头部尚未设置,则会创建该头部并赋予指定值。参数 value
可以是字符串或数组。
Note 注意
calling res.set()
after res.append()
will reset the previously-set header value.
在 res.append()
之后调用 res.set()
将重置之前设置的标头值。
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])
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.
将 HTTP 响应 Content-Disposition
头字段设置为“attachment”。如果提供了 filename
,则根据扩展名通过 res.type()
设置 Content-Type
,并设置 Content-Disposition
“filename=”参数。
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])
Sets cookie name
to value
. The value
parameter may be a string or object converted to JSON.
将 cookie name
设置为 value
。 value
参数可以是字符串或转换为 JSON 的对象。
The options
parameter is an object that can have the following properties.
options
参数是一个对象,可以包含以下属性。
Property 属性 | Type 类型 | Description 描述 |
---|---|---|
domain |
String 字符串 | Domain name for the cookie. Defaults to the domain name of the app. cookie 的域名。默认为应用的域名。 |
encode |
Function 函数 | A synchronous function used for cookie value encoding. Defaults to encodeURIComponent .用于 cookie 值编码的同步函数。默认为 encodeURIComponent 。 |
expires |
Date 日期 | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. Cookie 的 GMT 格式过期时间。若未指定或设为 0,则创建一个会话 Cookie。 |
httpOnly |
Boolean 布尔值 | Flags the cookie to be accessible only by the web server. 标记该 Cookie 仅可由网络服务器访问。 |
maxAge |
Number 数字 | Convenient option for setting the expiry time relative to the current time in milliseconds. 便捷选项,用于设置相对于当前时间的过期时间(以毫秒为单位)。 |
path |
String 字符串 | Path for the cookie. Defaults to “/”. Cookie 的路径,默认为“/”。 |
partitioned |
Boolean 布尔值 | Indicates that the cookie should be stored using partitioned storage. See Cookies Having Independent Partitioned State (CHIPS) for more details. 指示该 Cookie 应使用分区存储。更多详情请参阅《具有独立分区状态的 Cookie(CHIPS)》。 |
priority |
String 字符串 | Value of the “Priority” Set-Cookie attribute. “Priority” Set-Cookie 属性的值。 |
secure |
Boolean 布尔值 | Marks the cookie to be used with HTTPS only. 标记该 Cookie 仅限 HTTPS 使用。 |
signed |
Boolean 布尔值 | Indicates if the cookie should be signed. 指示该 Cookie 是否应被签名。 |
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. “SameSite” Set-Cookie 属性的值。更多信息请访问:https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1。 |
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.
res.cookie()
所做的只是根据提供的选项设置 HTTP Set-Cookie
头部。任何未指定的选项将默认为 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 })
You can set multiple cookies in a single response by calling res.cookie
multiple times, for example:
您可以通过多次调用 res.cookie
来在单个响应中设置多个 Cookie,例如:
res
.status(201)
.cookie('access_token', `Bearer ${token}`, {
expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours
})
.cookie('test', 'test')
.redirect(301, '/admin')
The encode
option allows you to choose the function used for cookie value encoding.
Does not support asynchronous functions.
encode
选项允许您选择用于 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.
使用示例:您需要为组织内的另一个站点设置一个跨域 cookie。该其他站点(不在您的管理控制下)未使用 URI 编码的 cookie 值。
// 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=/;'
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.
maxAge
选项是一个便捷选项,用于设置相对于当前时间的毫秒级“过期”时间。以下内容与上述第二个示例等效。
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
You can pass an object as the value
parameter; it is then serialized as JSON and parsed by bodyParser()
middleware.
您可以将一个对象作为 value
参数传递;随后它会被序列化为 JSON 并由 bodyParser()
中间件解析。
res.cookie('cart', { items: [1, 2, 3] })
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })
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.
使用 cookie-parser 中间件时,此方法还支持签名 cookie。只需包含设置为 true
的 signed
选项。然后, res.cookie()
将使用传递给 cookieParser(secret)
的密钥对值进行签名。
res.cookie('name', 'tobi', { signed: true })
Later, you may access this value through the req.signedCookies object.
之后,您可以通过 req.signedCookies 对象访问该值。
res.clearCookie(name [, options])
Clears the cookie specified by name
. For details about the options
object, see res.cookie().
清除由 name
指定的 cookie。有关 options
对象的详细信息,请参阅 res.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
.
Web 浏览器及其他兼容客户端仅当给定的 options
与传递给 res.cookie() 的参数(不包括 expires
和 maxAge
)完全一致时,才会清除该 cookie。
res.cookie('name', 'tobi', { path: '/admin' })
res.clearCookie('name', { path: '/admin' })
res.download(path [, filename] [, options] [, fn])
The optional options
argument is supported by Express v4.16.0 onwards.
可选参数 options
自 Express v4.16.0 起支持。
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 or
the root
option, if provided.
将 path
处的文件作为“附件”传输。通常,浏览器会提示用户下载。默认情况下, Content-Disposition
头部的“filename=”参数源自 path
参数,但可通过 filename
参数覆盖。若 path
为相对路径,则它将基于进程的当前工作目录或提供的 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 is secure if it contains user input or (b) set the root
option to the absolute path of a directory to contain access within.
此 API 提供对运行中文件系统数据的访问。确保(a)若 path
参数包含用户输入,则其构建方式是安全的;或(b)将 root
选项设置为目录的绝对路径以限制访问范围。
When the root
option is provided, Express will validate that the relative path provided as
path
will resolve within the given root
option.
当提供 root
选项时,Express 将验证作为 path
提供的相对路径是否能在给定的 root
选项内解析。
The following table provides details on the options
parameter.
下表提供了关于 options
参数的详细信息。
The optional options
argument is supported by Express v4.16.0 onwards.
Express v4.16.0 及以上版本支持可选的 options
参数。
Property 属性 | Description 描述 | Default 默认值 | Availability 可用性 |
---|---|---|---|
maxAge |
Sets the max-age property of the Cache-Control header in milliseconds or a string in ms format设置 Cache-Control 头的 max-age 属性,单位为毫秒或 ms 格式的字符串 |
0 | 4.16+ |
root |
Root directory for relative filenames. 相对文件名的根目录。 |
4.18+ | |
lastModified |
Sets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it.将 Last-Modified 头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。 |
Enabled 已启用 | 4.16+ |
headers |
Object containing HTTP headers to serve with the file. The header Content-Disposition will be overridden by the filename argument.包含与文件一起服务的 HTTP 头的对象。 Content-Disposition 头将被 filename 参数覆盖。 |
4.16+ | |
dotfiles |
Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. 用于服务点文件的选项。可能的值有“allow”、“deny”、“ignore”。 |
“ignore” “忽略” | 4.16+ |
acceptRanges |
Enable or disable accepting ranged requests. 启用或禁用接受范围请求。 |
true |
4.16+ |
cacheControl |
Enable or disable setting Cache-Control response header.启用或禁用设置 Cache-Control 响应头。 |
true |
4.16+ |
immutable |
Enable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.启用或禁用 Cache-Control 响应头中的 immutable 指令。若启用,还应指定 maxAge 选项以启用缓存。 immutable 指令将阻止支持的客户端在 maxAge 选项的生命周期内发起条件请求来检查文件是否已更改。 |
false |
4.16+ |
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.
该方法在传输完成或发生错误时调用回调函数 fn(err)
。若指定了回调函数且发生错误,回调函数必须明确处理响应过程,要么结束请求-响应循环,要么将控制权传递给下一个路由。
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]][, callback])
Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
结束响应过程。此方法实际上源自 Node 核心,特别是 http.ServerResponse 的 response.end()方法。
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.send()和 res.json()等方法。
res.end()
res.status(404).end()
res.format(object)
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.
当请求对象中存在 Accept
HTTP 头部时,执行内容协商。它利用 req.accepts()根据按质量值排序的可接受类型来选择请求的处理程序。若未指定该头部,则调用第一个回调函数。当未找到匹配项时,服务器会以 406“不可接受”响应,或调用 default
回调函数。
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()
.
选择回调函数时,会设置 Content-Type
响应头部。不过,您可以在回调函数内通过诸如 res.set()
或 res.type()
等方法修改此头部。
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”).
以下示例将在 Accept
头部字段设置为“application/json”或“*/json”时响应 { "message": "hey" }
(但如果它是“*/*”,则响应将为“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')
}
})
In addition to canonicalized MIME types, you may also use extension names mapped
to these types for a slightly less verbose implementation:
除了规范化的 MIME 类型外,您还可以使用映射到这些类型的扩展名来实现稍简洁的代码:
res.format({
text () {
res.send('hey')
},
html () {
res.send('<p>hey</p>')
},
json () {
res.send({ message: 'hey' })
}
})
res.get(field)
Returns the HTTP response header specified by field
.
The match is case-insensitive.
返回由 field
指定的 HTTP 响应头。匹配不区分大小写。
res.get('Content-Type')
// => "text/plain"
res.json([body])
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 响应。此方法发送一个响应(带有正确的内容类型),该响应是通过使用 JSON.stringify()将参数转换为 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.
该参数可以是任何 JSON 类型,包括对象、数组、字符串、布尔值、数字或 null,您还可以用它来将其他值转换为 JSON。
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
res.jsonp([body])
Sends a JSON response with JSONP support. This method is identical to res.json()
,
except that it opts-in to JSONP callback support.
发送一个支持 JSONP 的 JSON 响应。此方法与 res.json()
相同,只是它选择了支持 JSONP 回调。
res.jsonp(null)
// => callback(null)
res.jsonp({ user: 'tobi' })
// => callback({ "user": "tobi" })
res.status(500).jsonp({ error: 'message' })
// => callback({ "error": "message" })
By default, the JSONP callback name is simply callback
. Override this with the
jsonp callback name setting.
默认情况下,JSONP 回调名称仅为 callback
。可通过 jsonp 回调名称设置来覆盖此默认值。
The following are some examples of JSONP responses using the same code:
以下是使用相同代码的一些 JSONP 响应示例:
// ?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" })
res.links(links)
Joins the links
provided as properties of the parameter to populate the response’s
Link
HTTP header field.
将参数提供的 links
属性连接起来,以填充响应的 Link
HTTP 头部字段。
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)
Sets the response Location
HTTP header to the specified path
parameter.
将响应头 Location
设置为指定的 path
参数。
res.location('/foo/bar')
res.location('http://example.com')
After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location
header,
without any validation.
对 URL 进行编码后(若尚未编码),Express 会将指定的 URL 不经任何验证直接通过 Location
头发送给浏览器。
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.
浏览器负责从当前 URL 或引用 URL,以及 Location
头中指定的 URL 推导出目标 URL,并据此重定向用户。
res.redirect([status,] path)
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"
.
重定向到从指定的 path
派生的 URL,并带有指定的 status
,即一个对应于 HTTP 状态码的正整数。如果未指定, status
默认为 302 "Found"
。
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Redirects can be a fully-qualified URL for redirecting to a different site:
重定向可以是一个完全限定的 URL,用于跳转到不同的网站:
res.redirect('http://google.com')
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
:
重定向可以相对于主机名的根路径。例如,如果应用程序位于 http://example.com/admin/post/new
,以下操作将重定向到 URL http://example.com/admin
:
res.redirect('/admin')
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
.
重定向可以相对于当前 URL。例如,从 http://example.com/blog/admin/
(注意末尾的斜杠),以下操作将重定向到 URL http://example.com/blog/admin/post/new
。
res.redirect('post/new')
Redirecting to post/new
from http://example.com/blog/admin
(no trailing slash),
will redirect to http://example.com/blog/post/new
.
从 http://example.com/blog/admin
(无尾部斜杠)重定向到 post/new
,将跳转至 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.
如果你觉得上述行为令人困惑,不妨将路径段想象成目录(带有尾部斜杠)和文件,这样就会开始变得合理。
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
:
路径相对重定向也是可行的。如果你位于 http://example.com/admin/post/new
,以下操作将重定向到 http://example.com/admin/post
:
res.redirect('..')
See also Security best practices: Prevent open redirect
vulnerabilities.
另请参阅安全最佳实践:防止开放重定向漏洞。
res.render(view [, locals] [, callback])
res.render(视图 [, 局部变量] [, 回调函数])
Renders a view
and sends the rendered HTML string to the client.
Optional parameters:
渲染一个 view
并将渲染后的 HTML 字符串发送给客户端。可选参数:
locals
, an object whose properties define local variables for the view.
locals
,一个对象,其属性定义了视图的局部变量。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 invokesnext(err)
internally.
callback
,一个回调函数。如果提供,该方法将返回可能的错误和渲染后的字符串,但不会自动响应。当发生错误时,方法内部会调用next(err)
。
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.
参数 view
是一个字符串,表示要渲染的视图文件的路径。可以是绝对路径,或相对于 views
设置的路径。如果路径不包含文件扩展名,则由 view engine
设置决定文件扩展名。如果路径包含文件扩展名,则 Express 将通过 require()
加载指定模板引擎的模块,并使用加载模块的 __express
函数进行渲染。
For more information, see Using template engines with Express.
更多信息,请参阅在 Express 中使用模板引擎。
Warning 警告
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.
view
参数执行文件系统操作,如从磁盘读取文件和评估 Node.js 模块,出于安全考虑,不应包含来自最终用户的输入。
Warning 警告
The locals
object is used by view engines to render a response. The object
keys may be particularly sensitive and should not contain user-controlled
input, as it may affect the operation of the view engine or provide a path to
cross-site scripting. Consult the documentation for the used view engine for
additional considerations.
locals
对象被视图引擎用于渲染响应。该对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的操作或提供跨站脚本的途径。请查阅所用视图引擎的文档以获取更多注意事项。
Caution 注意
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.
局部变量 cache
启用视图缓存。将其设置为 true
,可在开发期间缓存视图;生产环境中默认启用视图缓存。
// 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])
Sends the HTTP response.
发送 HTTP 响应。
The body
parameter can be a Buffer
object, a String
, an object, Boolean
, or an Array
.
For example:
参数 body
可以是一个 Buffer
对象、一个 String
、一个对象、 Boolean
或一个 Array
。例如:
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' })
This method performs many useful tasks for simple non-streaming responses:
For example, it automatically assigns the Content-Length
HTTP response header field
and provides automatic HEAD and HTTP cache freshness support.
该方法为简单的非流式响应执行许多有用任务:例如,它自动分配 Content-Length
HTTP 响应头字段,并提供自动 HEAD 和 HTTP 缓存新鲜度支持。
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:
当参数为 Buffer
对象时,该方法将 Content-Type
响应头字段设置为“application/octet-stream”,除非之前已按如下方式定义:
res.set('Content-Type', 'text/html')
res.send(Buffer.from('<p>some html</p>'))
When the parameter is a String
, the method sets the Content-Type
to “text/html”:
当参数为 String
时,该方法将 Content-Type
设置为“text/html”:
res.send('<p>some html</p>')
When the parameter is an Array
or Object
, Express responds with the JSON representation:
当参数为 Array
或 Object
时,Express 会以 JSON 格式响应:
res.send({ user: 'tobi' })
res.send([1, 2, 3])
res.sendFile(path [, options] [, fn])
res.sendFile()
is supported by Express v4.8.0 onwards.
res.sendFile()
自 Express v4.8.0 起得到支持。
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.
传输指定路径 path
下的文件。根据文件扩展名设置响应 HTTP 头部字段 Content-Type
。除非在选项对象中设置了 root
选项,否则 path
必须是文件的绝对路径。
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.
此 API 提供对运行中文件系统数据的访问。确保 (a) 如果 path
参数包含用户输入,则将其构造为绝对路径的方式是安全的,或 (b) 将 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.
当提供 root
选项时,允许 path
参数为相对路径,包括包含 ..
的情况。Express 将验证作为 path
提供的相对路径是否会在给定的 root
选项内解析。
The following table provides details on the options
parameter.
下表提供了关于 options
参数的详细信息。
Property 属性 | Description 描述 | Default 默认值 | Availability 可用性 |
---|---|---|---|
maxAge |
Sets the max-age property of the Cache-Control header in milliseconds or a string in ms format设置 Cache-Control 头的 max-age 属性,单位为毫秒或 ms 格式的字符串 |
0 | |
root |
Root directory for relative filenames. 相对文件名的根目录。 |
||
lastModified |
Sets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it.将 Last-Modified 头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。 |
Enabled 已启用 | 4.9.0+ |
headers |
Object containing HTTP headers to serve with the file. 包含与文件一起提供的 HTTP 标头的对象。 |
||
dotfiles |
Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. 用于服务点文件的选项。可能的值有“allow”、“deny”、“ignore”。 |
“ignore” “忽略” | |
acceptRanges |
Enable or disable accepting ranged requests. 启用或禁用接受范围请求。 |
true |
4.14+ |
cacheControl |
Enable or disable setting Cache-Control response header.启用或禁用设置 Cache-Control 响应头。 |
true |
4.14+ |
immutable |
Enable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.启用或禁用 Cache-Control 响应头中的 immutable 指令。若启用,还应指定 maxAge 选项以启用缓存。 immutable 指令将阻止支持的客户端在 maxAge 选项的生命周期内发起条件请求来检查文件是否已更改。 |
false |
4.16+ |
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.
该方法在传输完成或发生错误时调用回调函数 fn(err)
。若指定了回调函数且发生错误,回调函数必须明确处理响应过程,要么结束请求-响应循环,要么将控制权传递给下一个路由。
Here is an example of using res.sendFile
with all its arguments.
以下是使用 res.sendFile
及其所有参数的示例。
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)
}
})
})
The following example illustrates using
res.sendFile
to provide fine-grained support for serving files:
以下示例展示了如何使用 res.sendFile
为文件服务提供细粒度的支持:
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.")
}
})
})
For more information, or if you have issues or concerns, see send.
如需更多信息或有任何问题或疑虑,请参阅 send。
res.sendStatus(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.
将响应 HTTP 状态码设置为 statusCode
,并发送已注册的状态消息作为文本响应体。如果指定了未知状态码,响应体将仅为该状态码数字。
res.sendStatus(404)
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.
某些版本的 Node.js 在将 res.statusCode
设置为无效的 HTTP 状态码(超出 100
到 599
的范围)时会抛出错误。请查阅所用 Node.js 版本的 HTTP 服务器文档。
res.set(field [, value])
res.set(字段 [, 值])
Sets the response’s HTTP header field
to value
.
To set multiple fields at once, pass an object as the parameter.
设置响应 HTTP 头 field
为 value
。如需一次性设置多个字段,可传入一个对象作为参数。
res.set('Content-Type', 'text/plain')
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
ETag: '12345'
})
Aliased as res.header(field [, value])
. 别名为 res.header(field [, value])
。
res.status(code)
Sets the HTTP status for the response.
It is a chainable alias of Node’s response.statusCode.
设置响应的 HTTP 状态码。它是 Node 中 response.statusCode 的可链式调用的别名。
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
res.type(type)
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 using the contentType()
method of the mime-types
package.
将 Content-Type
HTTP 头设置为由指定的 type
确定的 MIME 类型。如果 type
包含“/”字符,则直接将 Content-Type
设置为 type
的确切值;否则,假定其为文件扩展名,并使用 mime-types
包的 contentType()
方法查找对应的 MIME 类型。
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:
Aliased as res.contentType(type)
. 别名为 res.contentType(type)
。
res.vary(field)
Adds the field to the Vary
response header, if it is not there already.
如果字段尚未存在,则将其添加到 Vary
响应头中。
res.vary('User-Agent').render('docs')
Router 路由器
A router
object is an 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.
router
对象是一个中间件和路由的实例。你可以将其视为一个“迷你应用程序”,仅能执行中间件和路由功能。每个 Express 应用都有一个内置的应用路由器。
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.
路由器的行为类似于中间件本身,因此您可以将其作为参数传递给 app.use(),或者作为另一个路由器的 use()方法的参数。
The top-level express
object has a Router() method that creates a new router
object.
顶层的 express
对象拥有一个 Router()方法,用于创建一个新的 router
对象。
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:
一旦创建了路由器对象,您可以像应用程序一样向其添加中间件和 HTTP 方法路由(例如 get
、 put
、 post
等)。例如:
// 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) => {
// ..
})
You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.
然后,你可以通过这种方式为特定的根 URL 使用路由器,将路由分离到不同的文件甚至迷你应用中。
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router)
Keep in mind that any middleware applied to a router will run for all requests on that router’s path, even those that aren’t part of the router.
请记住,应用于路由器的任何中间件都会在该路由器路径上的所有请求上运行,即使这些请求不属于该路由器的一部分。
Methods 方法
router.all(path, [callback, ...] callback)
This method is just like the router.METHOD()
methods, except that it matches all HTTP methods (verbs).
此方法与 router.METHOD()
系列方法类似,不同之处在于它能匹配所有的 HTTP 方法(动词)。
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.
此方法对于为特定路径前缀或任意匹配项映射“全局”逻辑极为有用。例如,若你将以下路由定义置于所有其他路由定义之前,它将要求从此点开始的所有路由都需要认证,并自动加载用户。请注意,这些回调不必作为终点; loadUser
可以执行任务,然后调用 next()
以继续匹配后续路由。
router.all('{*splat}', requireAuthentication, loadUser)
Or the equivalent: 或等效于:
router.all('{*splat}', requireAuthentication)
router.all('{*splat}', loadUser)
Another example of this is white-listed “global” functionality. Here,
the example is much like before, but it only restricts paths prefixed with
“/api”:
另一个例子是白名单中的“全局”功能。此处示例与之前非常相似,但它仅限制以“/api”为前缀的路径:
router.all('/api/{*splat}', requireAuthentication)
router.METHOD(path, [callback, ...] callback)
router.METHOD(路径, [回调函数, ...] 回调函数)
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.METHOD()
方法提供了 Express 中的路由功能,其中 METHOD 是 HTTP 方法之一,如 GET、PUT、POST 等,均为小写形式。因此,实际的方法包括 router.get()
、 router.post()
、 router.put()
等。
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()
.
如果在 router.get()
之前未对路径调用 router.head()
,则 router.get()
函数除了 GET
方法外,还会自动为 HTTP HEAD
方法调用。
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.
您可以提供多个回调函数,它们会被同等对待,并且表现得像中间件一样,只不过这些回调函数可能会调用 next('route')
来跳过剩余的路由回调。您可以利用这一机制对路由执行前置条件检查,在没有理由继续执行匹配的路由时,将控制权传递给后续路由。
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”.
以下代码片段展示了最简单的路由定义方式。Express 将路径字符串转换为内部使用的正则表达式,用于匹配传入的请求。执行这些匹配时不考虑查询字符串,例如"GET /"会匹配以下路由,"GET /?name=tobi"同样也会匹配。
router.get('/', (req, res) => {
res.send('hello world')
})
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”.
你也可以使用正则表达式——这在有非常特定的约束时非常有用,例如以下表达式既能匹配“GET /commits/71dbb9c”,也能匹配“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}`)
})
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'
的 next
将导致该路由器上所有剩余的路由回调被绕过。
The following example illustrates next('router')
usage.
以下示例展示了 next('router')
的用法。
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)
router.param(名称, 回调函数)
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).
向路由参数添加回调触发器,其中 name
是参数名称, callback
是回调函数。虽然 name
在技术上是可选的,但从 Express v4.11.0 开始,不使用它的方法已被弃用(见下文)。
The parameters of the callback function are:
回调函数的参数包括:
req
, the request object.
req
,请求对象。res
, the response object.
res
,响应对象。next
, indicating the next middleware function.
next
,表示下一个中间件函数。- The value of the
name
parameter.
name
参数的值。 - The name of the parameter.
参数名称。
Unlike app.param()
, router.param()
does not accept an array of route parameters.
与 app.param()
不同, router.param()
不接受路由参数数组。
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.
例如,当路由路径中存在 :user
时,你可以将用户加载逻辑映射到该路由,自动提供 req.user
,或对参数输入执行验证。
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'))
}
})
})
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on router
will be triggered only by route parameters defined on router
routes.
参数回调函数的作用域仅限于定义它们的路由器。它们不会被挂载的应用或路由器继承,也不会因从父路由器继承的路由参数而触发。因此,在 router
上定义的参数回调仅由 router
路由上定义的路由参数触发。
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()
})
On GET /user/42
, the following is printed:
在 GET /user/42
上,将打印以下内容:
CALLED ONLY ONCE
although this matches
and this matches too
router.route(path)
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.
返回一个单一路由的实例,随后你可以用它通过可选中间件处理 HTTP 动词。使用 router.route()
以避免重复的路由命名及由此产生的输入错误。
Building on the router.param()
example above, the following code shows how to use
router.route()
to specify various HTTP method handlers.
基于上述 router.param()
示例,以下代码展示了如何使用 router.route()
来指定各种 HTTP 方法处理器。
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'))
})
This approach re-uses the single /users/:user_id
path and adds handlers for
various HTTP methods.
这种方法复用单一的 /users/:user_id
路径,并为各种 HTTP 方法添加处理程序。
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.route()
时,中间件的排序依据是路由创建的时间,而非方法处理程序添加到路由的时间。为此,你可以认为方法处理程序属于它们被添加到的路由。
router.use([path], [function, ...] function)
router.use([路径], [函数, ...] 函数)
Uses the specified middleware function or functions, with optional mount path path
, that defaults to “/”.
使用指定的中间件函数或函数组,带有可选的挂载路径 path
,默认为“/”。
This method is similar to app.use(). A simple example and use case is described below.
See app.use() for more information.
该方法类似于 app.use()。下面描述了一个简单的示例和用例。更多信息请参阅 app.use()。
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)
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.
“挂载”路径被剥离,对中间件函数不可见。此特性的主要效果是,挂载的中间件函数无需更改代码即可运行,无论其“前缀”路径名如何。
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.
使用 router.use()
定义中间件的顺序非常重要。它们会按顺序依次调用,因此顺序决定了中间件的优先级。例如,通常日志记录器会作为第一个使用的中间件,以确保每个请求都被记录。
const logger = require('morgan')
router.use(logger())
router.use(express.static(path.join(__dirname, 'public')))
router.use((req, res) => {
res.send('Hello')
})
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:
现在假设你想忽略对静态文件的日志记录请求,但继续记录在 logger()
之后定义的路由和中间件。你只需将调用 express.static()
的操作移到顶部,在添加日志中间件之前:
router.use(express.static(path.join(__dirname, 'public')))
router.use(logger())
router.use((req, res) => {
res.send('Hello')
})
Another example is serving files from multiple directories,
giving precedence to “./public” over the others:
另一个例子是从多个目录提供文件,优先考虑“./public”目录:
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))
The router.use()
method also supports named parameters so that your mount points
for other routers can benefit from preloading using named parameters.
router.use()
方法同样支持命名参数,这样其他路由器的挂载点也能受益于使用命名参数的预加载功能。
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)
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.
尽管身份验证中间件是通过 authRouter
添加的,但它也会在由 openRouter
定义的路由上运行,因为两个路由器都挂载在 /users
上。要避免这种行为,请为每个路由器使用不同的路径。