4.x API
Note备注
Express 4.0 requires Node.js 0.10 or higher.Express 4.0需要Node.js 0.10或更高版本。
express()
Creates an Express application. The 创建Express应用程序。express()
function is a top-level function exported by the express
module.express()
函数是express
模块导出的顶级函数。
var express = require('express')
var app = express()
Methods方法
express.json([options])
This middleware is available in Express v4.16.0 onwards.此中间件在Express v4.16.0及以后版本中可用。
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 返回只解析JSON并且只查看Content-Type
header matches the type
option. Content-Type
标头与type
选项匹配的请求的中间件。This parser accepts any
Unicode encoding of the body and supports automatic inflation of 此解析器接受正文的任何Unicode编码,并支持gzip
and
deflate
encodings.gzip
和deflate
编码的自动膨胀。
A new 在中间件之后,在请求对象上填充包含解析数据的新body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or an empty object ({}
) if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.body
对象(即req.body
),或者在没有要解析的主体、Content-Type
不匹配或发生错误的情况下填充空对象({}
)。
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.req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,在信任之前应该进行验证。
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.foo.toString()
可能会以多种方式失败,例如foo
可能不存在或可能不是字符串,toString
可能不是函数,而是字符串或其他用户输入。
The following table describes the properties of the optional 下表描述了可选options
object.options
对象的属性。
inflate |
Boolean | true |
|
limit |
Mixed | "100kb" |
|
reviver |
reviver option is passed directly to JSON.parse as the second argument. reviver 选项作为第二个参数直接传递给JSON.parse 。JSON.parse 的MDN文档中找到有关此参数的更多信息。 |
Function | null |
strict |
JSON.parse accepts.JSON.parse 接受的任何内容。 |
Boolean | true |
type |
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 ). type 选项将直接传递给type-is库,它可以是扩展名(如json )、mime类型(如application/json )或带通配符的mime类型(例如*/* 或*/json )。type option is called as fn(req) and the request is parsed if it returns a truthy value.type 选项被调用为fn(req) ,如果请求返回真值,则对其进行解析。 |
Mixed | "application/json" |
verify |
verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. verify(req, res, buf, encoding) 的形式调用,其中buf 是原始请求体的Buffer ,encoding 是请求的编码。 |
Function | undefined |
express.raw([options])
This middleware is available in Express v4.17.0 onwards.此中间件在Express v4.17.0及以后版本中可用。
This is a built-in middleware function in Express. 这是Express中内置的中间件功能。It parses incoming request
payloads into a 它将传入的请求有效载荷解析到Buffer
and is based on
body-parser.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. Buffer
,并且只在Content-Type
标头与type
选项匹配的情况下查看请求。This parser accepts
any Unicode encoding of the body and supports automatic inflation of 此解析器接受正文的任何Unicode编码,并支持gzip
and
deflate
encodings.gzip
和deflate
编码的自动膨胀。
A new 在中间件之后,在body
Buffer
containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or an empty object ({}
) if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.request
对象上填充包含解析数据的新body
Buffer
(即req.body
),或者在没有要解析的主体、Content-Type
不匹配或发生错误的情况下填充空对象({}
)。
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.req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,在信任之前应该进行验证。
For example, 例如,req.body.toString()
may fail in multiple ways, for example
stacking multiple parsers req.body
may be from a different parser. req.body.toString()
可能会以多种方式失败,例如堆叠多个解析器req.body
可能来自不同的解析器。Testing
that 建议在调用缓冲区方法之前测试req.body
is a Buffer
before calling buffer methods is recommended.req.body
是Buffer
。
The following table describes the properties of the optional 下表描述了可选options
object.options
对象的属性。
inflate |
Boolean | true |
|
limit |
Mixed | "100kb" |
|
type |
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/* ). type 选项将直接传递给type-is库,它可以是扩展名(如bin )、mime类型(如application/octet-stream )或带通配符的mime类型,如*/* 或application/* 。type option is called as fn(req) and the request is parsed if it returns a truthy value.type 选项被调用为fn(req) ,如果请求返回真值,则对其进行解析。 |
Mixed | "application/octet-stream" |
verify |
verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. verify(req, res, buf, encoding) 的形式调用,其中buf 是原始请求体的Buffer ,encoding 是请求的编码。 |
Function | undefined |
express.Router([options])
Creates a new router object.创建新的router对象。
var router = express.Router([options])
The optional 可选options
parameter specifies the behavior of the router.options
参数指定路由器的行为。
caseSensitive |
|||
mergeParams |
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 |
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
等)。
express.static(root, [options])
This is a built-in middleware function in Express.这是Express中内置的中间件功能。
It serves static files and is based on serve-static.它提供静态文件,基于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.root
参数指定从中提供静态资产的根目录。
The function determines the file to serve by combining 该函数通过将req.url
with the provided root
directory.req.url
与提供的root
目录组合来确定要服务的文件。
When a file is not found, instead of sending a 404 response, it calls 当找不到文件时,它不会发送404响应,而是调用next()
to move on to the next middleware, allowing for stacking and fall-backs.next()
继续下一个中间件,允许堆叠和回退。
The following table describes the properties of the 下表描述了options
object.
See also the example below.options
对象的属性。另请参阅下面的示例。
dotfiles |
See dotfiles below. |
String | undefined |
etag |
NOTE: express.static always sends weak ETags.express.static 总是发送弱etag。 |
Boolean | true |
extensions |
['html', 'htm'] .['html', 'htm'] 。 |
Mixed | false |
fallthrough |
See fallthrough below. |
Boolean | true |
immutable |
immutable directive in the Cache-Control response header. Cache-Control 响应标头中的immutable 指令。maxAge option should also be specified to enable caching. maxAge 选项以启用缓存。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 选项的生命周期内发出条件请求,以检查文件是否已更改。 |
Boolean | false |
index |
false to disable directory indexing.false 可禁用目录索引。 |
Mixed | “index.html” |
lastModified |
Last-Modified header to the last modified date of the file on the OS.Last-Modified 标头设置为操作系统上文件的最后修改日期。 |
Boolean | true |
maxAge |
Number | 0 | |
redirect |
Boolean | true |
|
setHeaders |
See setHeaders below. |
Function |
For more information, see Serving static files in Express.有关更多信息,请参阅在Express中提供静态文件,
and Using middleware - Built-in middleware.以及使用中间件——内置中间件。
dotfiles
Possible values for this option are:此选项的可能值为:
- “allow” -
No special treatment for dotfiles.对点档案没有特殊处理。 - “deny” -
Deny a request for a dotfile, respond with拒绝对点文件的请求,返回403
, then callnext()
.403
,然后调用next()
。 - “ignore” -
Act as if the dotfile does not exist, respond with假设点文件不存在,用404
, then callnext()
.404
响应,然后调用next()
。 undefined
-Act as ignore, except that files in a directory that begins with a dot are NOT ignored.充当忽略,但以点开头的目录中的文件不会被忽略。
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.next()
来调用堆栈中的下一个中间件。
When false, these errors (even 404s), will invoke 当为next(err)
.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. false
,这允许短路404以减少开销。This middleware will also reply to all methods.此中间件还将回复所有方法。
setHeaders
For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.对于此选项,指定一个函数来设置自定义响应标头。标题的更改必须同步进行。
The signature of the function is:函数的签名为:
fn(res, path, stat)
Arguments:论据:
res
, the response object.,响应对象。path
, the file path that is being sent.,正在发送的文件路径。stat
, the,正在发送的文件的stat
object of the file that is being sent.stat
对象。
Example of express.staticexpress.static的示例
Here is an example of using the 下面是一个使用express.static
middleware function with an elaborate options object:express.static
中间件函数和一个精心设计的选项对象的示例:
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
app.use(express.static('public', options))
express.text([options])
This middleware is available in Express v4.17.0 onwards.此中间件在Express v4.17.0及以后版本中可用。
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. Content-Type
标头与type
选项匹配的情况下查看请求。This parser accepts
any Unicode encoding of the body and supports automatic inflation of 此解析器接受正文的任何Unicode编码,并支持gzip
and
deflate
encodings.gzip
和deflate
编码的自动膨胀。
A new 在中间件之后,在body
string containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or an empty object ({}
) if
there was no body to parse, the Content-Type
was not matched, or an error
occurred.request
对象上填充包含解析数据的新body
字符串(即req.body
),或者在没有要解析的正文、Content-Type
不匹配或发生错误的情况下填充空对象({}
)。
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.req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,在信任之前应该进行验证。
For example, 例如,req.body.trim()
may fail in multiple ways, for example
stacking multiple parsers req.body
may be from a different parser. req.body.trim()
可能会以多种方式失败,例如堆叠多个解析器req.body
可能来自不同的解析器。Testing
that 建议在调用字符串方法之前测试req.body
is a string before calling string methods is recommended.req.body
是一个字符串。
The following table describes the properties of the optional 下表描述了可选options
object.options
对象的属性。
defaultCharset |
Content-Type header of the request.Content-Type 标头中未指定字符集,请指定文本内容的默认字符集。 |
String | "utf-8" |
inflate |
Boolean | true |
|
limit |
Mixed | "100kb" |
|
type |
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/* ). type 选项将直接传递给type-is库,它可以是扩展名(如txt )、mime类型(如text/plain )或带通配符的mime类型,如*/* 或text/* 。type option is called as fn(req) and the request is parsed if it returns a truthy value.type 选项被调用为fn(req) ,如果请求返回真值,则对其进行解析。 |
Mixed | "text/plain" |
verify |
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])
This middleware is available in Express v4.16.0 onwards.此中间件在Express v4.16.0及以后版本中可用。
This is a built-in middleware function in Express. It parses incoming requests
with urlencoded payloads and is based on body-parser.这是Express中内置的中间件功能。它使用url编码的有效载荷解析传入的请求,并基于body-parser。
Returns middleware that only parses urlencoded bodies and only looks at
requests where the 返回的中间件仅解析url编码的主体,并且只查找Content-Type
header matches the type
option. Content-Type
标头与类型选项匹配的请求。This
parser accepts only UTF-8 encoding of the body and supports automatic
inflation of 此解析器只接受正文的UTF-8编码,并支持gzip
and deflate
encodings.gzip
和deflate
编码的自动膨胀。
A new 在中间件之后,在body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
), or an empty object ({}
) if
there was no body to parse, the Content-Type
was not matched, or an error
occurred. request
对象上填充包含解析数据的新body
对象(即req.body
),或者在没有要解析的主体、内容类型不匹配或发生错误的情况下填充空对象({}
)。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
).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.req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,在信任之前应该进行验证。
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.foo.toString()
可能会以多种方式失败,例如foo
可能不存在或可能不是字符串,toString
可能不是函数,而是字符串或其他用户输入。
The following table describes the properties of the optional 下表描述了可选options
object.options
对象的属性。
extended |
querystring library (when false ) or the qs library (when true ). querystring 库(false 时)或qs库(true 时)解析URL编码数据之间进行选择。 |
Boolean | true |
inflate |
Boolean | true |
|
limit |
Mixed | "100kb" |
|
parameterLimit |
Number | 1000 |
|
type |
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 ). type 选项直接传递给type-is库,这可以是扩展名(如urlencoded )、mime类型(如application/x-www-form-urlencoded )或带通配符的mime类型,如*/x-www-form-urlencoded 。type option is called as fn(req) and the request is parsed if it returns a truthy value.type 选项被调用为fn(req) ,如果请求返回真值,则对其进行解析。 |
Mixed | "application/x-www-form-urlencoded" |
verify |
verify(req, res, buf, encoding) , where buf is a Buffer of the raw request body and encoding is the encoding of the request. verify(req, res, buf, encoding) ,其中buf 是原始请求体的Buffer ,encoding 是请求的编码。 |
Function | undefined |
depth |
qs library when extended is true . extended 为true 时,配置qs 库的最大深度。32 . It is recommended to keep this value as low as possible.32 。建议将此值保持尽可能低。 |
Number | 32 |
The Express v4.20.0中添加了depth
option was added in Express v4.20.0. If you are using an earlier version, this option will not be available.depth
选项。如果您使用的是早期版本,则此选项将不可用。
Application
The app
object conventionally denotes the Express application.app
对象通常表示Express应用程序。
Create it by calling the top-level 通过调用express模块导出的顶级express()
function exported by the Express module:express()
函数来创建它:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(3000)
The app
object has methods forapp
对象具有以下方法
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 Express应用程序对象可以从请求对象和响应对象分别引用为req.app
, and res.app
, respectively.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. locals
对象来呈现响应。对象键可能特别敏感,不应包含用户控制的输入,因为它可能会影响视图引擎的运行或提供跨站点脚本的路径。Consult the documentation for the used view engine for
additional considerations.有关其他注意事项,请参阅所用视图引擎的文档。
console.dir(app.locals.title)
// => 'My App'
console.dir(app.locals.email)
// => '[email protected]'
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 = '[email protected]'
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
的一个实例,可用于处理对路线的请求。
var express = require('express')
var app = express() // the main app
var admin = express() // the sub app
admin.get('/', function (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
会返回它所挂载的模式列表,如下例所示。
var admin = express()
admin.get('/', function (req, res) {
console.dir(admin.mountpath) // [ '/adm*n', '/manager' ]
res.send('Admin Homepage')
})
var secret = express()
secret.get('/', function (req, res) {
console.log(secret.mountpath) // /secr*t
res.send('Admin Secret')
})
admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app
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.有关详细信息,请参阅应用程序设置。
var admin = express()
admin.on('mount', function (parent) {
console.log('Admin Mounted')
console.log(parent) // refers to the parent app
})
admin.get('/', function (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参数
path |
|
'/' (root path) |
---|---|---|
callback |
|
None |
Examples示例
The following callback is executed for requests to 无论是使用GET、POST、PUT、DELETE还是任何其他HTTP请求方法,都会对/secret
whether using
GET, POST, PUT, DELETE, or any other HTTP request method:/secret
的请求执行以下回调:
app.all('/secret', function (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. app.all()
方法对于映射特定路径前缀或任意匹配的“全局”逻辑非常有用。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.loadUser
可以执行任务,然后调用next()
继续匹配后续路由。
app.all('*', requireAuthentication, loadUser)
Or the equivalent:或等效物:
app.all('*', requireAuthentication)
app.all('*', 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/*', requireAuthentication)
app.delete(path, callback [, callback ...])
Routes HTTP DELETE requests to the specified path with the specified callback functions.使用指定的回调函数将HTTP DELETE请求路由到指定的路径。
For more information, see the routing guide.有关更多信息,请参阅路线指南。
Arguments参数
path |
|
'/' (root path) |
---|---|---|
callback |
|
None |
Example示例
app.delete('/', function (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.name
设置为false
,其中name
是应用程序设置表中的属性之一。
Calling 对布尔属性调用app.set('foo', false)
for a Boolean property is the same as calling app.disable('foo')
.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.name
设置为true
,其中name
是应用程序设置表中的属性之一。
Calling 为布尔属性调用app.set('foo', true)
for a Boolean property is the same as calling app.enable('foo')
.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 默认情况下,Express将根据文件扩展名require()
the engine based on the file extension.require()
引擎。
For example, if you try to render a “foo.pug” file, Express invokes the
following internally, and caches the 例如,如果您尝试渲染“foopug”文件,Express会在内部调用以下内容,并在后续调用中缓存require()
on subsequent calls to increase
performance.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 在这种情况下,EJS提供了一个.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..renderFile()
方法,该方法具有Express所期望的相同签名:(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无缝协作。
var 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:name
app设置的值,其中name
是app设置表中的字符串之一。例如:
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参数
path |
|
'/' |
---|---|---|
callback |
|
None |
For more information, see the routing guide.有关更多信息,请参阅路线指南。
Example示例
app.get('/', function (req, res) {
res.send('GET request to homepage')
})
app.listen(path, [callback])
Starts a UNIX socket and listens for connections on the given path. 启动UNIX套接字并侦听给定路径上的连接。This method is identical to Node’s http.Server.listen().此方法与Node的http.Server.listen()完全相同。
var express = require('express')
var app = express()
app.listen('/tmp/sock')
app.listen([port[, host[, backlog]]][, callback])
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,操作系统将分配一个任意未使用的端口,这对于自动化任务(测试等)等情况很有用。
var express = require('express')
var 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. express()
返回的app
实际上是一个JavaScript函数,旨在作为回调传递给Node的HTTP服务器以处理请求。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):这使得为应用程序的HTTP和HTTPS版本提供相同的代码库变得容易,因为应用程序不会继承这些代码(它只是一个回调):
var express = require('express')
var https = require('https')
var http = require('http')
var 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 () {
var 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 ...])
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 路由HTTP请求,其中METHOD是请求的HTTP方法,如GET、PUT、POST等,小写。因此,实际的方法是app.get()
,
app.post()
, app.put()
, and so on. See Routing methods below for the complete list.app.get()
、app.post()
、app.put()
等。有关完整列表,请参阅下面的路由方法。
Arguments参数
Argument | Description | Default |
---|---|---|
path |
|
'/' (root path) |
callback |
|
None |
Routing methods路由方法
Express supports the following routing methods corresponding to the HTTP methods of the same names:Express支持与同名HTTP方法对应的以下路由方法:
checkout
copy
delete
get
head
lock
merge
mkactivity
mkcol
move
m-search
notify
options
patch
post
purge
put
report
search
subscribe
trace
unlock
unsubscribe
The API documentation has explicit entries only for the most popular HTTP methods API文档中只有最流行的HTTP方法app.get()
,
app.post()
, app.put()
, and app.delete()
.app.get()
、app.post()
、app.put()
和app.delete()
的显式条目。
However, the other methods listed above work in exactly the same way.然而,上面列出的其他方法的工作方式完全相同。
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, 要路由转换为无效JavaScript变量名的方法,请使用括号表示法。例如,app['m-search']('/', function ...
.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()
,则除了GET
方法外,还会自动为HTTP HEAD
方法调用app.get()
函数。
The method, 方法app.all()
, is not derived from any HTTP method and loads middleware at
the specified path for all HTTP request methods.app.all()
不是从任何HTTP方法派生出来的,它在所有HTTP请求方法的指定路径上加载中间件。
For more information, see app.all.有关更多信息,请参阅app.all。
For more information on routing, see the routing guide.有关路由的更多信息,请参阅路由指南。
app.param([name], callback)
Add callback triggers to route parameters, where 在路由参数中添加回调触发器,其中name
is the name of the parameter or an array of them, and callback
is the callback function. name
是参数的名称或它们的数组,callback
是回调函数。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.回调函数的参数依次是请求对象、响应对象、下一个中间件、参数值和参数名称。
If 如果name
is an array, the callback
trigger is registered for each parameter declared in it, in the order in which they are declared. name
是一个数组,则会按照声明的顺序为其中声明的每个参数注册callback
触发器。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. next
将调用下一个声明参数的回调函数。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.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
出现在路由路径中时,您可以映射用户加载逻辑以自动向路由提供请求者,或对参数输入进行验证。
app.param('user', function (req, res, next, id) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function (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
路由上定义的路由参数触发。
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', function (req, res, next, id) {
console.log('CALLED ONLY ONCE')
next()
})
app.get('/user/:id', function (req, res, next) {
console.log('although this matches')
next()
})
app.get('/user/:id', function (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'], function (req, res, next, value) {
console.log('CALLED ONLY ONCE with', value)
next()
})
app.get('/user/:id/:page', function (req, res, next) {
console.log('although this matches')
next()
})
app.get('/user/:id/:page', function (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
The following section describes 以下部分描述了app.param(callback)
, which is deprecated as of v4.11.0.app.param(callback)
,该回调自v4.11.0起已弃用。
The behavior of the 只需向app.param(name, callback)
method can be altered entirely by passing only a function to app.param()
. app.param()
传递一个函数,就可以完全改变app.param(name, callback)
方法的行为。This function is a custom implementation of how 此函数是app.param(name, callback)
should behave - it accepts two parameters and must return a middleware.app.param(name, callback)
行为的自定义实现,它接受两个参数,必须返回一个中间件。
The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.此函数的第一个参数是应该捕获的URL参数的名称,第二个参数可以是任何可能用于返回中间件实现的JavaScript对象。
The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.函数返回的中间件决定了捕获URL参数时的行为。
In this example, the 在这个例子中,app.param(name, callback)
signature is modified to app.param(name, accessId)
. Instead of accepting a name and a callback, app.param()
will now accept a name and a number.app.param(name, callback)
签名被修改为app.param(name, accessId)
。app.param()
现在将接受名称和数字,而不是接受名称和回调。
var express = require('express')
var app = express()
// customizing the behavior of app.param()
app.param(function (param, option) {
return function (req, res, next, val) {
if (val === option) {
next()
} else {
next('route')
}
}
})
// using the customized app.param()
app.param('id', 1337)
// route to trigger the capture
app.get('/user/:id', function (req, res) {
res.send('OK')
})
app.listen(3000, function () {
console.log('Ready')
})
In this example, the 在这个例子中,app.param(name, callback)
signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.app.param(name, callback)
签名保持不变,但定义了一个自定义数据类型检查函数来验证用户id的数据类型,而不是中间件回调。
app.param(function (param, validator) {
return function (req, res, next, val) {
if (validator(val)) {
next()
} else {
next('route')
}
}
})
app.param('id', function (candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate)
})
The ‘“.
’ character can’t be used to capture a character in your capturing regexp. .
”字符不能用于在捕获正则表达式中捕获字符。For example you can’t use 例如,您不能使用'/user-.+/'
to capture 'users-gami'
, use [\\s\\S]
or [\\w\\W]
instead (as in '/user-[\\s\\S]+/'
.'/user-.+/'
以捕获'users-gami'
,请改用[\\s\\S]
或[\\w\\W]
(如'/user-[\\s\\S]+/'
)。
Examples:例如:
// captures '1-a_6' but not '543-azser-sder'
router.get('/[0-9]+-[[\\w]]*', function (req, res, next) { next() })
// captures '1-a_6' and '543-az(ser"-sder' but not '5-a s'
router.get('/[0-9]+-[[\\S]]*', function (req, res, next) { next() })
// captures all (equivalent to '.*')
router.get('[[\\s\\S]]*', function (req, res, next) { next() })
app.path()
Returns the canonical path of the app, a string.返回应用程序的规范路径,一个字符串。
var app = express()
var blog = express()
var blogAdmin = express()
app.use('/blog', blog)
blog.use('/admin', blogAdmin)
console.dir(app.path()) // ''
console.dir(blog.path()) // '/blog'
console.dir(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 ...])
Routes HTTP POST requests to the specified path with the specified callback functions.
For more information, see the routing guide.使用指定的回调函数将HTTP POST请求路由到指定的路径有关详细信息,请参阅路由指南。
Arguments参数
path |
|
'/' (root path) |
---|---|---|
callback |
|
None |
Example示例
app.post('/', function (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参数
path |
|
'/' |
---|---|---|
callback |
|
None |
Example示例
app.put('/', function (req, res) {
res.send('PUT request to homepage')
})
app.render(view, [locals], callback)
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. callback
函数返回视图的渲染HTML。它接受一个可选参数,该参数是一个包含视图局部变量的对象。It is like res.render(),
except it cannot send the rendered view to the client on its own.它类似于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. locals
对象来呈现响应。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.有关其他注意事项,请参阅所用视图引擎的文档。
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', function (err, html) {
// ...
})
app.render('email', { name: 'Tobi' }, function (err, html) {
// ...
})
app.route(path)
Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware.返回单个路由的实例,然后您可以使用该实例通过可选中间件处理HTTP谓词。
Use 使用app.route()
to avoid duplicate route names (and thus typo errors).app.route()
避免重复的路由名称(从而避免拼写错误)。
var app = express()
app.route('/events')
.all(function (req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function (req, res, next) {
res.json({})
})
.post(function (req, res, next) {
// maybe add a new event...
})
app.set(name, value)
Assigns setting 将设置name
to value
. name
分配给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.这些特殊名称列在应用程序设置表中。
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')
相同。同样地,对Boolean属性调用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
的值,即使它有默认值(为了向后兼容性);子应用程序在生产环境中不会继承view cache
的值(当NODE_ENV
为“production”时)。
Property | |||
---|---|---|---|
|
Boolean |
NOTE |
N/A (undefined) |
|
String |
|
|
|
Varied |
|
|
|
String |
“callback” |
|
|
Boolean |
NOTE |
N/A (undefined) |
|
Varied | NOTE |
N/A (undefined) |
|
Varied | NOTE |
N/A (undefined) |
|
Varied |
|
"extended" |
|
Boolean |
NOTE |
N/A (undefined) |
|
Number | 2 | |
|
Varied |
NOTE |
|
|
String or Array |
|
|
|
Boolean |
NOTE |
|
|
String | NOTE |
N/A (undefined) |
|
Boolean |
|
Options for `trust proxy` settingtrust proxy
的设置选项
Read Express behind proxies for more
information.阅读代理背后的Express以获取更多信息。
Value | |
---|---|
Boolean |
|
|
|
Number |
|
Function |
|
Options for `etag` settingetag
的设置选项
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.ETag功能是使用etag包实现的。
For more information, see its documentation.有关更多信息,请参阅其文档。
Boolean |
|
String |
|
Function |
|
app.use([path,] callback [, callback...])
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参数
path |
|
'/' |
---|---|---|
callback |
|
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.path
默认为“/”,因此对应用程序的每个请求都将执行没有路径的中间件。
For example, this middleware function will be executed for every request to the app:例如,将对应用程序的每个请求执行此中间件函数:
app.use(function (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(function (req, res, next) {
res.send('Hello World')
})
// requests will never reach this route
app.get('/', function (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. next
对象,也必须指定它来维护签名。Otherwise, the 否则,next
object will be interpreted as regular middleware and will fail to handle errors. next
对象将被解释为常规中间件,无法处理错误。For details about error-handling middleware, see: Error handling.有关错误处理中间件的详细信息,请参阅:错误处理。
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature 以与其他中间件函数相同的方式定义错误处理中间件函数,除了使用四个参数而不是三个参数,特别是使用签名(err, req, res, next)
):(err, req, res, next)
:
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Path examples路径示例
The following table provides some simple examples of valid 下表提供了安装中间件的有效path
values for
mounting middleware.path
值的一些简单示例。
|
|
|
|
|
|
|
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()
.app.use()
、app.METHOD()
和app.all()
的callback
参数。
|
|
|
|
Array |
|
|
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. req
对象表示HTTP请求,并具有请求查询字符串、参数、正文、HTTP标头等属性。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响应为res
),但其实际名称由您正在使用的回调函数的参数决定。
For example:例如:
app.get('/user/:id', function (req, res) {
res.send('user ' + req.params.id)
})
But you could just as well have:但你也可以:
app.get('/user/:id', function (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, 在Express 4中,默认情况下req.files
is no longer available on the req
object by default. req.files
在req
对象上不再可用。To access uploaded files
on the 要访问req.files
object, use multipart-handling middleware like busboy, multer,
formidable,
multiparty,
connect-multiparty,
or pez.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 = function (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:
var greet = express.Router()
greet.get('/jp', function (req, res) {
console.log(req.baseUrl) // /greet
res.send('Konnichiwa!')
})
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). baseUrl
属性也会返回匹配的字符串,而不是模式。In the
following example, the 在以下示例中,greet
router is loaded on two path patterns.greet
路由器加载在两种路径模式上。
app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}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. req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,在信任之前应该进行验证。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.foo.toString()
可能会以多种方式失败,例如foo
可能不存在或可能不是字符串,toString
可能不是函数,而是字符串或其他用户输入。
The following example shows how to use body-parsing middleware to populate 以下示例显示了如何使用body解析中间件来填充req.body
.req.body
。
var express = require('express')
var 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', function (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. 使用cookie-parser中间件时,此属性是一个包含请求发送的cookie的对象。If the request contains no cookies, it defaults to 如果请求不包含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.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. trust proxy
设置未评估为false
时,此属性将从X-Forwarded-Host
标头字段获取值。This header can be set by
the client or by the proxy.此标头可以由客户端或代理设置。
If there is more than one 如果请求中有多个X-Forwarded-Host
header in the request, the
value of the first header is used. X-Forwarded-Host
标头,则使用第一个标头的值。This includes a single header with
comma-separated values, in which the first value is used.这包括一个逗号分隔值的单个标头,其中使用了第一个值。
Prior to Express v4.17.0, the 在Express v4.17.0之前,X-Forwarded-Host
could not contain multiple
values or be present more than once.X-Forwarded-Host
不能包含多个值或出现多次。
// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'
req.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. trust proxy
设置未计算为false
时,此属性的值将从X-Forwarded-For
标头中最左侧的条目中导出。This header can be set by the client or by the proxy.此标头可以由客户端或代理设置。
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. trust proxy
设置未计算为false
时,此属性包含X-Forwarded-For
请求标头中指定的IP地址数组。Otherwise, it contains an
empty array. This header can be set by the client or by the proxy.否则,它包含一个贫血的数组。此标头可以由客户端或代理设置。
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:
包含与请求的HTTP方法相对应的字符串:GET
, POST
, PUT
, and so on.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. req.url
;但是,它保留了原始请求URL,允许您出于内部路由目的自由重写req.url
。For example,
the “mounting” feature of app.use() will rewrite 例如,app.use()的“挂载”特性将重写req.url
to strip the mount point.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
的组合。考虑以下示例:
app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?sort=desc'
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
是第n个捕获组。This rule is applied to unnamed wild card matches with string routes such as 此规则适用于具有字符串路由(如/file/*
:/file/*
)的未命名通配符匹配:
// 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 Express会自动解码req.params
(using decodeURIComponent
).req.params
中的值(使用decodeURIComponent
)。
req.path
Contains the path part of the request URL.包含请求URL的路径部分。
// example.com/users?sort=desc
console.dir(req.path)
// => '/users'
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.trust proxy
设置未评估为false
时,此属性将使用X-Forwarded-Proto
标头字段的值(如果存在)。
This header can be set by the client or by the proxy.此标头可以由客户端或代理设置。
console.dir(req.protocol)
// => 'http'
req.query
This property is an object containing a property for each query string parameter in the route.此属性是一个对象,包含路由中每个查询字符串参数的属性。
When query parser is set to disabled, it is an empty object 当查询解析器设置为禁用时,它是一个空对象{}
, otherwise it is the result of the configured query parser.{}
,否则它是配置的查询解析器的结果。
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. req.query
的形状基于用户控制的输入,因此此对象中的所有属性和值都是不受信任的,应在信任之前进行验证。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.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. qs
模块,默认情况下使用它。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
模块可以通过许多设置进行配置,可能需要使用与默认设置不同的设置来填充req.query
:
var qs = require('qs')
app.set('query parser', function (str) {
return 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?', function userIdHandler (req, res) {
console.log(req.route)
res.send('GET')
})
Example output from the previous snippet:上一段代码的示例输出:
{ path: '/user/:id?',
stack:
[ { handle: [Function: userIdHandler],
name: 'userIdHandler',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/?$/i,
method: 'get' } ],
methods: { get: true } }
req.secure
A Boolean property that is true if a TLS connection is established. Equivalent to:一个布尔属性,如果建立了TLS连接,则为true
。相当于:
console.dir(req.protocol === 'https')
// => true
req.signedCookies
When using cookie-parser middleware, this property
contains signed cookies sent by the request, unsigned and ready for use. 使用cookie-parser中间件时,此属性包含由请求发送的已签名cookie、未签名cookie和可供使用的cookie。Signed cookies reside
in a different object to show developer intent; otherwise, a malicious attack could be placed on
签名的Cookie驻留在不同的对象中,以显示开发人员的意图;否则,req.cookie
values (which are easy to spoof). req.cookie
值(很容易被欺骗)可能会受到恶意攻击。Note that signing a cookie does not make it “hidden”
or encrypted; but simply prevents tampering (because the secret used to sign is private).请注意,对cookie进行签名并不会使其“隐藏”或加密;但只是防止篡改(因为用于签名的秘密是私有的)。
If no signed cookies are sent, the property defaults to 如果没有发送签名的Cookie,则属性默认为{}
.{}
。
// 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. subdomain offset
默认为2,用于确定子域段的起始位置。To change this behavior, change its value
using app.set.要更改此行为,请使用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.Accept
HTTP标头字段检查指定的内容类型是否可接受。
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"
).false
(在这种情况下,应用程序应返回406 "Not Acceptable"
)。
The 类型值可以是单个MIME类型字符串(如“application/json”)、扩展名(如“json”)、逗号分隔的列表或数组。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).对于list或array,该方法返回最佳匹配(如果有的话)。
// 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.Accept-Charset
HTTP标头字段,返回指定字符集的第一个被接受的字符集。
If none of the specified charsets is accepted, returns 如果指定的字符集都不被接受,则返回false
.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.Accept-Encoding
HTTP标头字段,返回指定编码的第一个被接受的编码。
If none of the specified encodings is accepted, returns 如果指定的编码都不被接受,则返回false
.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.Accept-Language
HTTP标头字段,返回指定语言中第一个被接受的语言。
If none of the specified languages is accepted, returns 如果指定的语言都不被接受,则返回false
.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 (4.x) source: Express(4x)来源:request.js line 179
Accepts (1.3) source: 接受(1.3)来源:index.js line 195
req.get(field)
Returns the specified HTTP request header field (case-insensitive match).返回指定的HTTP请求标头字段(不区分大小写的匹配)。
The Referrer
and Referer
fields are interchangeable.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 如果传入请求的“content-type”HTTP标头字段与type
parameter. type
参数指定的MIME类型匹配,则返回匹配的内容类型。If the request has no body, returns 如果请求没有正文,则返回null
. Returns false
otherwise.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/*'
// Using arrays
// When Content-Type is application/json
req.is(['json', 'html'])
// => 'json'
// Using multiple arguments
// When Content-Type is application/json
req.is('json', 'html')
// => 'json'
req.is('html')
// => false
req.is(['xml', 'yaml'])
// => false
req.is('xml', 'yaml')
// => false
For more information, or if you have issues or concerns, see type-is.有关更多信息,或者如果您有问题或疑虑,请参阅type-is。
req.param(name [, defaultValue])
Deprecated. Use either 已弃用。根据需要,使用req.params
, req.body
or req.query
, as applicable.req.params
、req.body
或req.query
。
Returns the value of param 返回参数name
when present.name
的值(如果存在)。
// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
Lookup is performed in the following order:查找按以下顺序执行:
req.params
req.body
req.query
Optionally, you can specify 如果在任何请求对象中都找不到该参数,则可以指定defaultValue
to set a default value if the parameter is not found in any of the request objects.defaultValue
来设置默认值。
Direct access to 为了清楚起见,应该倾向于直接访问req.body
, req.params
, and req.query
should be favoured for clarity - unless you truly accept input from each object.req.body
、req.params
和req.query
——除非你真的接受每个对象的输入。
Body-parsing middleware must be loaded for 必须加载正文解析中间件,req.param()
to work predictably. Refer req.body for details.req.param()
才能按预期工作。详情请参阅req.body。
req.range(size[, options])
Range
header parser.标头解析器。
The size
parameter is the maximum size of the resource.size
参数是资源的最大大小。
The options
parameter is an object that can have the following properties.options
参数是一个可以具有以下属性的对象。
combine |
Boolean | 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发出格式错误的标头字符串的信号-1
signals an unsatisfiable range表示范围不令人满意
// parse header from request
var range = req.range(1000)
// the type of the range
if (range.type === 'bytes') {
// the ranges
range.forEach(function (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', function (req, res) {
res.send('user ' + req.params.id)
})
But you could just as well have:但你也可以:
app.get('/user/:id', function (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('/', function (req, res) {
console.dir(res.headersSent) // false
res.send('OK')
console.dir(res.headersSent) // true
})
res.locals
Use this property to set variables accessible in templates rendered with res.render.使用此属性可以设置在使用res.render渲染的模板中可访问的变量。
The variables set on 在res.locals
are available within a single request-response cycle, and will not
be shared between requests.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. locals
对象来呈现响应。对象键可能特别敏感,不应包含用户控制的输入,因为它可能会影响视图引擎的运行或提供跨站点脚本的路径。Consult the documentation for the used view engine for
additional considerations.有关其他注意事项,请参阅所用视图引擎的文档。
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(function (req, res, next) {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user
res.locals.authenticated = !req.user.anonymous
next()
})
Methods方法
res.append(field [, value])
Note备注
res.append()
is supported by Express v4.11.0+受Express v4.11.0+的支持
Appends the specified 将指定value
to the HTTP response header field
. value
附加到HTTP响应标头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
参数可以是字符串或数组。
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 将HTTP响应Content-Disposition
header field to “attachment”. Content-Disposition
标头字段设置为“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.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 将cookiename
to value
. The value
parameter may be a string or object converted to JSON.name
设置为value
。value
参数可以是转换为JSON的字符串或对象。
The options
parameter is an object that can have the following properties.options
参数是一个可以具有以下属性的对象。
domain |
String | |
encode |
Function | encodeURIComponent .encodeURIComponent 。 |
expires |
Date | |
httpOnly |
Boolean | |
maxAge |
Number | |
path |
String | |
partitioned |
Boolean | |
priority |
String | |
secure |
Boolean | |
signed |
Boolean | |
sameSite |
Boolean or String |
All res.cookie()
does is set the HTTP Set-Cookie
header with the options provided.res.cookie()
所做的就是使用提供的选项设置HTTP Set-Cookie
标头。
Any option not specified defaults to the value stated in RFC 6265.任何未指定的选项默认为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,并由bodyPaser()
中间件解析。
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. 当使用cookie-parser中间件时,此方法也支持签名的cookie。Simply include the 只需将signed
option set to true
.signed
选项设置为true
即可。
Then 然后res.cookie()
will use the secret passed to cookieParser(secret)
to sign the value.res.cookie()
将使用传递给cookieParser(secret)
的secret
对值进行签名。
res.cookie('name', 'tobi', { signed: true })
Later you may access this value through the req.signedCookie object.稍后,您可以通过req.signedCookie对象访问此值。
res.clearCookie(name [, options])
Clears the cookie with the specified 通过发送name
by sending a Set-Cookie
header that sets its expiration date in the past.Set-Cookie
标头来清除具有指定name
的cookie,该标头设置了过去的过期日期。
This instructs the client that the cookie has expired and is no longer valid. 这指示客户端cookie已过期,不再有效。For more information
about available 有关可用options
, see res.cookie().options
的更多信息,请参阅res.cookie()。
If the 如果设置了maxAge
or expires
options are set, the cookie may not be cleared depending on the time values provided,
as Express does not ignore these options. maxAge
或expires
选项,则根据提供的时间值,cookie可能不会被清除,因为Express不会忽略这些选项。It is therefore recommended to omit these options when calling this
method. Passing these two options has been deprecated since Express v4.20.0.因此,建议在调用此方法时省略这些选项。自Express v4.20.0以来,传递这两个选项已被弃用。
Web browsers and other compliant clients will only clear the cookie if the given
Web浏览器和其他兼容客户端只有在给定的options
is identical to those given to res.cookie(), excluding
expires
and maxAge
.options
与res.cookie()的选项相同时才会清除cookie,但不包括expires
和maxAge
。
res.cookie('name', 'tobi', { path: '/admin' })
res.clearCookie('name', { path: '/admin' })
res.download(path [, filename] [, options] [, fn])
Transfers the file at 将path
as an “attachment”. path
中的文件作为“附件”传输。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.Content-Disposition
标头“filename=”参数从path
参数派生,但可以用filename
参数覆盖。
If 如果path
is relative, then it will be based on the current working directory of the process or
the root
option, if provided.path
是相对的,那么它将基于进程的当前工作目录或root
选项(如果提供)。
This API provides access to data on the running file system. 此API提供对正在运行的文件系统上的数据的访问。Ensure that either (a) the way in
which the 确保(a)如果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.path
参数包含用户输入,则其构造方式是安全的,或者(b)将根选项设置为包含访问权限的目录的绝对路径。
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 Express v4.16.0及以后版本支持可选options
argument is supported by Express v4.16.0 onwards.options
参数。
maxAge |
Cache-Control header in milliseconds or a string in ms formatCache-Control 标头的max-age属性(以毫秒为单位)或ms格式的字符串 |
0 | 4.16+ |
root |
4.18+ | ||
lastModified |
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 |
Content-Disposition will be overridden by the filename argument.Content-Disposition 将被filename 参数覆盖。 |
4.16+ | |
dotfiles |
“ignore” | 4.16+ | |
acceptRanges |
true |
4.16+ | |
cacheControl |
Cache-Control response header.Cache-Control 响应标头。 |
true |
4.16+ |
immutable |
immutable directive in the Cache-Control response header. Cache-Control 响应标头中的immutable 指令。maxAge option should also be specified to enable caching. maxAge 选项以启用缓存。immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.maxAge 选项的生命周期内发出条件请求,以检查文件是否已更改。 |
false |
4.16+ |
The method invokes the callback function 当传输完成或发生错误时,该方法调用回调函数fn(err)
when the transfer is complete
or when an error occurs. fn(err)
。If the callback function is specified and an error occurs,
the callback function must explicitly handle the response process either by
ending the request-response cycle, or by passing control to the next route.如果指定了回调函数并发生错误,则回调函数必须通过结束请求-响应周期或将控制传递给下一个路由来显式处理响应过程。
res.download('/report-12345.pdf')
res.download('/report-12345.pdf', 'report.pdf')
res.download('/report-12345.pdf', 'report.pdf', function (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.Accept
HTTP标头(如果存在)执行内容协商。
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.它使用req.accepts()根据可接受类型的质量值顺序为请求选择处理程序。如果未指定标头,则调用第一个回调。
When no match is found, the server responds with 406 “Not Acceptable”, or invokes the 当没有找到匹配项时,服务器会返回406“Not Acceptable”,或调用default
callback.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': function () {
res.send('hey')
},
'text/html': function () {
res.send('<p>hey</p>')
},
'application/json': function () {
res.send({ message: 'hey' })
},
default: function () {
// 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: function () {
res.send('hey')
},
html: function () {
res.send('<p>hey</p>')
},
json: function () {
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 发送支持JSONP的JSON响应。此方法与res.json()
,
except that it opts-in to JSONP callback support.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 默认情况下,JSONP回调名称只是callback
. Override this with the
jsonp callback name setting.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
HTTP标头设置为指定的path
参数。
res.location('/foo/bar')
res.location('http://example.com')
res.location('back')
Note备注
'back'
was deprecated in 4.21.0, use req.get('Referrer') || '/'
as an argument instead.'back'
在4.21.0中被弃用,请使用req.get('Referrer') || '/'
作为参数。
A path
value of “back” has a special meaning, it refers to the URL specified in the Referer
header of the request. If the Referer
header was not specified, it refers to “/”.path
值“back”具有特殊含义,它指的是请求的Referer
标头中指定的URL。如果未指定Referer
标头,则它引用“/”。
See also Security best practices: Prevent open redirect
vulnerabilities.另请参阅安全最佳实践:防止开放重定向漏洞。
After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the 对URL进行编码后(如果尚未编码),Express会在Location标头中将指定的URL传递给浏览器,而不进行任何验证。Location
header,
without any validation.
Browsers take the responsibility of deriving the intended URL from the current URL
or the referring URL, and the URL specified in the 浏览器负责从当前URL、引用URL和Location
header; and redirect the user accordingly.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 .path
导出的URL,具有指定的status
,一个与HTTP状态代码对应的正整数。
If not specified, 如果未指定,status
defaults to “302 “Found”.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
,以下内容将重定向到URLhttp://example.com/admin
:
res.redirect('/admin')
Redirects can be relative to the current URL. For example,
from 重定向可以相对于当前URL。例如,从http://example.com/blog/admin/
(notice the trailing slash), the following
would redirect to the URL http://example.com/blog/admin/post/new
.http://example.com/blog/admin/
(注意后面的斜线),以下内容将重定向到URLhttp://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
.post/new
从http://example.com/blog/admin
(无尾随斜线),将重定向到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('..')
A back
redirection redirects the request back to the referer,
defaulting to /
when the referer is missing.back
重定向将请求重定向回referer,默认为/
当引用者丢失时。
res.redirect('back')
Note
back
redirect was deprecated in 4.21.0, use req.get('Referrer') || '/'
as an argument instead.back
重定向在4.21.0中被弃用,请使用req.get('Referrer') || '/'
作为参数。
See also Security best practices: Prevent open redirect
vulnerabilities.另请参阅安全最佳实践:防止开放重定向漏洞。
res.render(view [, locals] [, callback])
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.,其属性定义视图局部变量的对象。callback
, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response.,一个回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。When an error occurs, the method invokes当发生错误时,该方法在内部调用next(err)
internally.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. view
参数是一个字符串,是要渲染的视图文件的文件路径。这可以是绝对路径,也可以是相对于views
设置的路径。If the path does not contain a file extension, then the 如果路径不包含文件扩展名,则view engine
setting determines the file extension. view engine
设置将确定文件扩展名。If the path does contain a file extension, then Express will load the module for the specified template engine (via 如果路径确实包含文件扩展名,则Express将为指定的模板引擎加载模块(通过require()
) and render it using the loaded module’s __express
function.require()
),并使用加载的模块的__express
函数进行渲染。
For more information, see Using template engines with Express.有关更多信息,请参阅在Express中使用模板引擎。
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. locals
对象来呈现响应。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.有关其他注意事项,请参阅所用视图引擎的文档。
The local variable 局部变量缓存启用视图cache
enables view caching. cache
。Set it to 将其设置为true
,
to cache the view during development; view caching is enabled in production by default.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', function (err, html) {
res.send(html)
})
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
// ...
})
res.req
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
(unless previously defined) 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
响应头字段设置为“应用程序/八位字节流”,除非之前定义如下:
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.受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. path
传输文件。根据文件扩展名设置Content-Type响应HTTP标头字段。Unless the 除非在root
option is set in
the options object, path
must be an absolute path to the file.options
对象中设置了根选项,否则path
必须是文件的绝对路径。
This API provides access to data on the running file system. 此API提供对正在运行的文件系统上的数据的访问。Ensure that either (a) the way in
which the 确保(a)如果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.path
参数包含用户输入,则将其构造为绝对路径的方式是安全的,或者(b)将root
选项设置为包含访问权限的目录的绝对路径。
When the 当提供root
option is provided, the path
argument is allowed to be a relative path,
including containing ..
. root
选项时,允许path
参数是相对路径,包括包含..
。Express will validate that the relative path provided as Express将验证作为path
will
resolve within the given root
option.path
提供的相对路径是否会在给定的root
选项内解析。
The following table provides details on the 下表提供了options
parameter.options
参数的详细信息。
maxAge |
Cache-Control header in milliseconds or a string in ms formatCache-Control 标头的最大年龄属性(以毫秒为单位)或ms格式的字符串 |
0 | |
root |
|||
lastModified |
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 |
|||
dotfiles |
“ignore” | ||
acceptRanges |
true |
4.14+ | |
cacheControl |
Cache-Control response header.Cache-Control 响应标头。 |
true |
4.14+ |
immutable |
immutable directive in the Cache-Control response header. Cache-Control 响应标头中的immutable 指令。maxAge option should also be specified to enable caching. maxAge 选项以启用缓存。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 选项的生命周期内发出条件请求,以检查文件是否已更改。 |
false |
4.16+ |
The method invokes the callback function 当传输完成或发生错误时,该方法调用回调函数fn(err)
when the transfer is complete
or when an error occurs. fn(err)
。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.如果指定了回调函数并发生错误,则回调函数必须通过结束请求-响应周期或将控制传递给下一个路由来显式处理响应过程。
Here is an example of using 下面是一个使用res.sendFile
with all its arguments.res.sendFile
及其所有参数的示例。
app.get('/file/:name', function (req, res, next) {
var options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
}
var fileName = req.params.name
res.sendFile(fileName, options, function (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', function (req, res) {
var uid = req.params.uid
var file = req.params.file
req.user.mayViewFilesFrom(uid, function (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 将响应HTTP状态代码设置为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.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
). res.statusCode
设置为无效的HTTP状态码(在100
到599
的范围之外)时,Node.js的某些版本会抛出。Consult
the HTTP server documentation for the Node.js version being used.有关正在使用的Node.js版本,请参阅HTTP服务器文档。
res.set(field [, value])
Sets the response’s HTTP header 将响应的HTTP标头field
to value
.
To set multiple fields at once, pass an object as the parameter.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.设置response的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
. Content-Type
HTTP标头设置为由指定type
确定的MIME类型。If 如果type
contains the “/” character, then it sets the Content-Type
to the exact value of type
, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the express.static.mime.lookup()
method.type
包含“/”字符,则将Content-Type
设置为type
的确切值,否则将假定为文件扩展名,并使用express.static.mime.lookup()
方法在映射中查找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. router
对象是中间件和路由的实例。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.你可以把它看作是一个“迷你应用程序”,只能执行中间件和路由功能。每个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 创建路由器对象后,您可以像应用程序一样向其添加中间件和HTTP方法路由(如get
, put
, post
,
and so on) to it just like an application. For example:get
、put
、post
等)。例如:
// invoked for any requests passed to this router
router.use(function (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', function (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('*', requireAuthentication, loadUser)
Or the equivalent:或等效物:
router.all('*', requireAuthentication)
router.all('*', 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/*', requireAuthentication)
router.METHOD(path, [callback, ...] callback)
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. router.METHOD()
方法在Express中提供路由功能,其中METHOD是HTTP方法之一,如GET、PUT、POST等,小写。Thus, the actual methods are 因此,实际的方法是router.get()
, router.post()
,
router.put()
, and so on.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()
,则除了GET
方法外,HTTP HEAD方法也会自动调用router.get()
函数。
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). next('route')
来绕过其余的路由回调。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.您可以使用此机制对路线执行条件,然后在没有理由继续匹配路线时将控制权传递给后续路线。
The following snippet illustrates the most simple route definition possible.
Express translates the path strings to regular expressions, used internally
to match incoming requests. 以下代码段说明了最简单的路由定义。Express将路径字符串转换为正则表达式,在内部用于匹配传入请求。Query strings are not considered when performing
these matches, for example “GET /” would match the following route, as would
“GET /?name=tobi”.执行这些匹配时不考虑查询字符串,例如“GET/”将匹配以下路由,“GET /?name=tobi”也是如此。
router.get('/', function (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/cocommits/71dbbjc..4c084f9”。
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) {
var from = req.params[0]
var to = req.params[1] || 'HEAD'
res.send('commit range ' + from + '..' + to)
})
router.param(name, callback)
Adds callback triggers to route parameters, where 向路由参数添加回调触发器,其中name
is the name of the parameter and callback
is the callback function. name
是参数的名称,callback
是回调函数。Although 虽然name
is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).name
在技术上是可选的,但从Express v4.11.0开始,不推荐使用此方法(见下文)。
The parameters of the callback function are:回调函数的参数如下:
req
, the request object.,请求对象。res
, the response object.,响应对象。next
, indicating the next middleware function.,指示下一个中间件功能。The value of thename
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
出现在路由路径中时,您可以映射用户加载逻辑以自动向路由提供请求者,或对参数输入进行验证。
router.param('user', function (req, res, next, id) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function (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', function (req, res, next, id) {
console.log('CALLED ONLY ONCE')
next()
})
router.get('/user/:id', function (req, res, next) {
console.log('although this matches')
next()
})
router.get('/user/:id', function (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
The following section describes 以下部分描述了router.param(callback)
, which is deprecated as of v4.11.0.router.param(callback)
,它从v4.11.0开始就被弃用了。
The behavior of the 只需向router.param(name, callback)
method can be altered entirely by passing only a function to router.param()
. router.param()
传递一个函数,就可以完全改变router.param(name, callback)
方法的行为。This function is a custom implementation of how 此函数是router.param(name, callback)
should behave - it accepts two parameters and must return a middleware.router.param(name, callback)
行为的自定义实现,它接受两个参数,必须返回一个中间件。
The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.此函数的第一个参数是应该捕获的URL参数的名称,第二个参数可以是任何可能用于返回中间件实现的JavaScript对象。
The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.函数返回的中间件决定了捕获URL参数时的行为。
In this example, the 在这个例子中,router.param(name, callback)
signature is modified to router.param(name, accessId)
. Instead of accepting a name and a callback, router.param()
will now accept a name and a number.router.param(name, callback)
签名被修改为router.param(name, accessId)
。router.param()
现在将接受名称和数字,而不是接受名称和回调。
var express = require('express')
var app = express()
var router = express.Router()
// customizing the behavior of router.param()
router.param(function (param, option) {
return function (req, res, next, val) {
if (val === option) {
next()
} else {
res.sendStatus(403)
}
}
})
// using the customized router.param()
router.param('id', '1337')
// route to trigger the capture
router.get('/user/:id', function (req, res) {
res.send('OK')
})
app.use(router)
app.listen(3000, function () {
console.log('Ready')
})
In this example, the 在这个例子中,router.param(name, callback)
signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.router.param(name, callback)
签名保持不变,但定义了一个自定义数据类型检查函数来验证用户id的数据类型,而不是中间件回调。
router.param(function (param, validator) {
return function (req, res, next, val) {
if (validator(val)) {
next()
} else {
res.sendStatus(403)
}
}
})
router.param('id', function (candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate)
})
router.route(path)
Returns an instance of a single route which you can then use to handle HTTP verbs
with optional middleware. 返回单个路由的实例,然后您可以使用该实例通过可选中间件处理HTTP verbs。Use 使用router.route()
to avoid duplicate route naming and
thus typing errors.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方法处理程序。
var router = express.Router()
router.param('user_id', function (req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id: id,
name: 'TJ'
}
next()
})
router.route('/users/:user_id')
.all(function (req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next()
})
.get(function (req, res, next) {
res.json(req.user)
})
.put(function (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(function (req, res, next) {
next(new Error('not implemented'))
})
.delete(function (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)
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.此方法类似于app.use()。下面描述了一个简单的示例和用例。
See app.use() for more information.有关更多信息,请参阅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.中间件就像一个管道:请求从定义的第一个中间件函数开始,沿着中间件堆栈“向下”处理它们匹配的每条路径。
var express = require('express')
var app = express()
var router = express.Router()
// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function (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', function (req, res, next) {
// ... maybe some additional /bar logging ...
next()
})
// always invoked
router.use(function (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. router.use()
定义中间件的顺序非常重要。它们是按顺序调用的,因此顺序定义了中间件的优先级。For example,
usually a logger is the very first middleware you would use, so that every request gets logged.例如,通常记录器是您使用的第一个中间件,这样每个请求都会被记录下来。
var logger = require('morgan')
var path = require('path')
router.use(logger())
router.use(express.static(path.join(__dirname, 'public')))
router.use(function (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()
. logger()
后定义的路由和中间件。You would simply move the call to 在添加记录器中间件之前,您只需将express.static()
to the top,
before adding the logger middleware:express.static()
的调用移到顶部:
router.use(express.static(path.join(__dirname, 'public')))
router.use(logger())
router.use(function (req, res) {
res.send('Hello')
})
Another example is serving files from multiple directories,
giving precedence to “./public” over the others:另一个例子是提供来自多个目录的文件,使“./public”优先于其他目录:
router.use(express.static(path.join(__dirname, 'public')))
router.use(express.static(path.join(__dirname, 'files')))
router.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:因此,如果路由匹配,通过一个路由器添加的中间件可以为其他路由器运行。例如,此代码显示安装在同一路径上的两个不同路由器:
var authRouter = express.Router()
var openRouter = express.Router()
authRouter.use(require('./authenticate').basic(usersdb))
authRouter.get('/:user_id/edit', function (req, res, next) {
// ... Edit user UI ...
})
openRouter.get('/', function (req, res, next) {
// ... List users ...
})
openRouter.get('/:user_id', function (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
. authRouter
添加的,它也会在openRouter
定义的路由上运行,因为这两个路由器都安装在/users
上。To avoid this behavior, use different paths for each router.为了避免这种行为,请为每个路由器使用不同的路径。