🌐 Nodejs.cn

请求

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

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

属性

🌐 Properties

req 对象包含许多属性,这些属性提供有关 HTTP 请求的信息,例如头信息、查询参数等。

🌐 The req object contains a number of properties that provide information about the HTTP request, such as headers, query parameters, and more.

req.accepted

返回一个按质量从高到低排序的已接受媒体类型数组。

🌐 Return an array of Accepted media types ordered from highest quality to lowest.

[
{ "value": "application/json", "quality": 1, "type": "application", "subtype": "json" },
{ "value": "text/html", "quality": 0.5, "type": "text", "subtype": "html" }
]

req.acceptedCharsets

返回一个按质量从高到低排序的已接受字符集数组。

🌐 Return an array of Accepted charsets ordered from highest quality to lowest.

Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8
// => ['unicode-1-1', 'iso-8859-5']

req.acceptedLanguages

返回一个按质量从高到低排序的已接受语言数组。

🌐 Return an array of Accepted languages ordered from highest quality to lowest.

Accept-Language: en;q=.5, en-us
// => ['en-us', 'en']

req.body

此属性是一个包含已解析请求体的对象。此功能由 bodyParser() 中间件提供,尽管其他请求体解析中间件也可能遵循此约定。当使用 bodyParser() 时,此属性默认为 {}

🌐 This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

index.js
// POST user[name]=tobi&user[email]=tobi@learnboost.com
console.log(req.body.user.name);
// => "tobi"
console.log(req.body.user.email);
// => "tobi@learnboost.com"
// POST { "name": "tobi" }
console.log(req.body.name);
// => "tobi"

req.cookies

此对象使用需要 cookieParser() 中间件。它包含由用户代理发送的 cookie。如果未发送任何 cookie,则默认为 {}

🌐 This object requires the cookieParser() middleware for use. It contains cookies sent by the user-agent. If no cookies are sent, it defaults to {}.

index.js
// Cookie: name=tj
console.log(req.cookies.name);
// => "tj"

req.files

该属性是已上传文件的对象。此功能由 bodyParser() 中间件提供,虽然其他请求体解析中间件也可能遵循此约定。当使用 bodyParser() 时,该属性默认为 {}

🌐 This property is an object of the files uploaded. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

例如,如果一个 文件 字段被命名为“image”,并且上传了一个文件,req.files.image 将包含以下 File 对象:

{ size: 74643,
path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
name: 'edge.png',
type: 'image/png',
hash: false,
lastModifiedDate: Thu Aug 09 2012 20:07:51 GMT-0700 (PDT),
_writeStream:
{ path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
fd: 13,
writable: false,
flags: 'w',
encoding: 'binary',
mode: 438,
bytesWritten: 74643,
busy: false,
_queue: [],
_open: [Function],
drainable: true },
length: [Getter],
filename: [Getter],
mime: [Getter] }

bodyParser() 中间件利用了

🌐 The bodyParser() middleware utilizes the

node-formidable 模块在内部使用,并接受相同的选项。一个例子是 keepExtensions formidable 选项,默认值为 false ,在这种情况下,会给你一个文件名 “/tmp/8ef9c52abe857867fd0a4e9a819d1876”,没有 “.png” 扩展名。要启用此选项以及其他选项,你可以将它们传递给 bodyParser()

app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' }));

req.fresh

检查请求是否是新的——也就是 Last-Modified 和/或 ETag 是否仍然匹配,表明资源是“新鲜的”.

🌐 Check if the request is fresh - aka Last-Modified and/or the ETag still match, indicating that the resource is “fresh”.

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

req.host

从“Host”头字段返回主机名(不包含端口号)。

🌐 Returns the hostname from the “Host” header field (void of port number).

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

req.ip

返回远程地址,或者在启用“信任代理”时 - 上游地址。

🌐 Return the remote address, or when “trust proxy” is enabled - the upstream address.

console.dir(req.ip);
// => '127.0.0.1'

req.ips

当“trust proxy”为true时,解析“X-Forwarded-For”IP地址列表并返回一个数组,否则返回一个空数组。

🌐 When “trust proxy” is true, parse the “X-Forwarded-For” ip address list and return an array, otherwise an empty array is returned.

例如,如果值是“client, proxy1, proxy2”,你将收到数组 ["client", "proxy1", "proxy2"],其中“proxy2”是最下游的。

🌐 For example if the value were “client, proxy1, proxy2” you would receive the array ["client", "proxy1", "proxy2"] where “proxy2” is the furthest down-stream.

req.originalUrl

此属性非常像 req.url,但是它保留原始请求的 URL,允许你自由重写 req.url 以用于内部路由。例如,app.use() 的“挂载”功能将重写 req.url,以去掉挂载点。

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

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

req.params

此属性是一个数组,包含映射到命名路由“parameters”的属性。例如,如果你有路由 /user/:name,那么“name”属性可以通过 req.params.name 访问。此对象的默认值为 {}

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

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

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

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

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

req.path

返回请求的 URL 路径名。

🌐 Returns the request URL pathname.

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

req.protocol

当请求使用 TLS 时,返回协议字符串 “http” 或 “https”。当启用 “trust proxy” 设置时,将信任 “X-Forwarded-Proto” 头字段。如果你在提供 https 的反向代理后运行,这可以启用。

🌐 Return the protocol string “http” or “https” when requested with TLS. When the “trust proxy” setting is enabled the “X-Forwarded-Proto” header field will be trusted. If you’re running behind a reverse proxy that supplies https for you this may be enabled.

console.dir(req.protocol);
// => 'http'

req.query

此属性是一个包含已解析查询字符串的对象,默认值为 {}

🌐 This property is an object containing the parsed query-string, defaulting to {}.

// GET /search?q=tobi+ferret
console.dir(req.query.q);
// => 'tobi ferret'
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
console.dir(req.query.order);
// => 'desc'
console.dir(req.query.shoe.color);
// => 'blue'
console.dir(req.query.shoe.type);
// => 'converse'

req.res

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

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

req.route

当前匹配的 Route 包含多个属性,例如路由的原始路径字符串、生成的正则表达式等等。

🌐 The currently matched Route containing several properties such as the route’s original path string, the regexp generated, and so on.

app.get('/user/:id?', function (req, res) {
console.dir(req.route);
});

前一个代码片段的示例输出:

🌐 Example output from the previous snippet:

{ path: '/user/:id?',
method: 'get',
callbacks: [ [Function] ],
keys: [ { name: 'id', optional: true } ],
regexp: /^\/user(?:\/([^\/]+?))?\/?$/i,
params: [ id: '12' ] }

req.secure

检查是否已建立 TLS 连接。这是以下内容的简写:

🌐 Check if a TLS connection is established. This is a short-hand for:

console.dir(req.protocol === 'https');
// => true

req.signedCookies

此对象使用时需要 cookieParser(secret) 中间件。它包含用户代理发送的已签名 cookie,并且未签名,可以直接使用。已签名的 cookie 存放在不同的对象中以显示开发者的意图;否则,req.cookie 值可能会受到恶意攻击(这些值很容易被伪造)。请注意,签名 cookie 并不意味着它是“隐藏”或加密的;这仅仅是防止篡改(因为用于签名的密钥是私有的)。如果没有发送已签名的 cookie,则默认为 {}

🌐 This object requires the cookieParser(secret) middleware for use. It contains signed cookies sent by the user-agent, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on req.cookie values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; this simply prevents tampering (because the secret used to sign is private). If no signed cookies are sent, it defaults to {}.

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

req.stale

检查请求是否过时——即 Last-Modified 和/或 ETag 不匹配,表明资源已“过时”。

🌐 Check if the request is stale - aka Last-Modified and/or the ETag do not match, indicating that the resource is “stale”.

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

req.subdomains

将子域作为数组返回。

🌐 Return subdomains as an array.

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

req.xhr

检查请求是否使用 ‘X-Requested-With’ 头字段设置为 ‘XMLHttpRequest’(例如 jQuery 等)发出。

🌐 Check if the request was issued with the “X-Requested-With” header field set to “XMLHttpRequest” (jQuery etc).

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

方法

🌐 Methods

req 对象还包含许多可用于执行与 HTTP 请求相关的各种任务的方法,例如检查内容类型、获取头部值等。

🌐 The req object also contains a number of methods that can be used to perform various tasks related to the HTTP request, such as checking the content type, retrieving header values, and more.

req.accepts(types)

检查所给的 types 是否可接受,如果可接受则返回最佳匹配,否则返回 undefined —— 在这种情况下,你应该响应 406 “不可接受”。

🌐 Check if the given types are acceptable, returning the best match when true, otherwise undefined - in which case you should respond with 406 “Not Acceptable”.

type 值可以是单个 MIME 类型字符串,例如 “application/json”,扩展名,例如 “json”,逗号分隔的列表或数组。当提供列表或数组时,将返回最佳匹配(如果有的话)。

🌐 The type value may be a single mime type string such as “application/json”, the extension name such as “json”, a comma-delimited list or an array. When a list or array is given the best match, if any is returned.

index.js
// 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');
// => undefined
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
req.accepts('html, json');
// => "json"

req.acceptsCharset(charset)

检查给定的 charset 是否可接受。

🌐 Check if the given charset are acceptable.

req.acceptsLanguage(语言)

🌐 req.acceptsLanguage(lang)

检查给定的 lang 是否可接受。

🌐 Check if the given lang are acceptable.

req.get(field)

获取不区分大小写的请求头 field。“Referrer” 和 “Referer” 字段可以互换。

🌐 Get the case-insensitive request header field. The “Referrer” and “Referer” fields are interchangeable.

req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined

别名为 req.header(field)

🌐 Aliased as req.header(field).

req.is(type)

检查传入请求是否包含 “Content-Type” 头字段,并且它与给定的 mime type 匹配。

🌐 Check if the incoming request contains the “Content-Type” header field, and it matches the give mime type.

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

req.param(name)

当存在时,返回参数 name 的值。

🌐 Return the value of param name when present.

// ?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

为了清晰起见,应优先直接访问 req.bodyreq.paramsreq.query——除非你确实接受来自每个对象的输入。

🌐 Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.