请求对象
req 对象表示 HTTP 请求,并具有请求查询字符串、参数、正文、HTTP 头等属性。在本指南中,并且按照惯例,该对象总是被称为 req(HTTP 响应则为 res),但它的实际名称取决于你正在使用的回调函数的参数。
🌐 The req object represents the HTTP request and has properties for the
request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention,
the object is always referred to as req (and the HTTP response is res) but its actual name is determined
by the parameters to the callback function in which you’re working.
例如:
🌐 For example:
app.get('/user/:id', function (req, res) { res.send('user ' + req.params.id);});import { type Request, type Response } from 'express';
app.get('/user/:id', function (req: Request, res: Response) { 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);});import { type Request, type Response } from 'express';
app.get('/user/:id', function (request: Request, response: Response) { response.send('user ' + request.params.id);});req 对象是 Node 自带请求对象的增强版本,并支持所有 内置字段和方法。
🌐 The req object is an enhanced version of Node’s own request object
and supports all built-in fields and methods.
属性
🌐 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.
Caution
在 Express 4 中,req.files 默认不再可用在 req 对象上。要访问 req.files 对象上的上传文件,请使用处理 multipart 的中间件,如 multer、multiparty、busboy、formidable 或 pez。
🌐 In Express 4, req.files is no longer available on the req object by default. To access uploaded files
on the req.files object, use multipart-handling middleware like multer, multiparty, busboy,
formidable,
or pez.
req.app
此属性保存对正在使用该中间件的 Express 应用实例的引用。
🌐 This property holds a reference to the instance of the Express application that is using the middleware.
如果你遵循这样的模式:创建一个只导出中间件函数的模块,并在你的主文件中 require() 它,那么中间件可以通过 req.app 访问 Express 实例
🌐 If you follow the pattern in which you create a module that just exports a middleware function
and require() it in your main file, then the middleware can access the Express instance via req.app
例如:
🌐 For example:
app.get('/viewdirectory', require('./mymiddleware.cjs'));import mymiddleware from './mymiddleware.mjs';
app.get('/viewdirectory', mymiddleware);而中间件模块本身:
🌐 And the middleware module itself:
module.exports = function (req, res) { res.send('The views directory is ' + req.app.get('views'));};export default function (req, res) { res.send('The views directory is ' + req.app.get('views'));}import { type Request, type Response } from 'express';
export default function (req: Request, res: Response) { res.send('The views directory is ' + req.app.get('views'));}req.baseUrl
路由实例挂载的 URL 路径。
🌐 The URL path on which a router instance was mounted.
req.baseUrl 属性类似于 app 对象的 mountpath 属性,除非 app.mountpath 返回匹配的路径模式。
🌐 The req.baseUrl property is similar to the mountpath property of the app object,
except app.mountpath returns the matched path pattern(s).
例如:
🌐 For example:
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'import { type Request, type Response } from 'express';
const greet = express.Router();
greet.get('/jp', function (req: Request, res: Response) { console.log(req.baseUrl); // /greet res.send('Konnichiwa!');});
app.use('/greet', greet); // load the router on '/greet'即使你使用路径模式或一组路径模式来加载路由,baseUrl 属性返回的是匹配的字符串,而不是模式。在下面的示例中,greet 路由在两个路径模式下被加载。
🌐 Even if you use a path pattern or a set of path patterns to load the router,
the baseUrl property returns the matched string, not the pattern(s). In the
following example, the greet router is loaded on two path patterns.
app.use(['/gre+t', '/hel{2}o'], greet); // load the router on '/gre+t' and '/hel{2}o'当向 /greet/jp 发出请求时,req.baseUrl 是 “/greet”。当向 /hello/jp 发出请求时,req.baseUrl 是 “/hello”。
🌐 When a request is made to /greet/jp, req.baseUrl is “/greet”. When a request is
made to /hello/jp, req.baseUrl is “/hello”.
req.body
包含在请求体中提交的数据的键值对。
默认情况下,它是 undefined,并且在使用如 express.json() 或 express.urlencoded() 这样的请求体解析中间件时会被填充。
🌐 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().
Warning
由于 req.body 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能会以多种方式失败,例如 foo 可能不存在或可能不是字符串,而 toString 可能不是函数,而是字符串或其他用户输入。
🌐 As req.body’s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, req.body.foo.toString() may
fail in multiple ways, for example foo may not be there or may not be a string, and toString
may not be a function and instead a string or other user-input.
以下示例显示了如何使用 body-parsing 中间件来填充 req.body。
🌐 The following example shows how to use body-parsing middleware to populate req.body.
var express = require('express');
var app = express();
app.use(express.json()); // for parsing application/jsonapp.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);});import express from 'express';
const app = express();
app.use(express.json()); // for parsing application/jsonapp.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);});import express, { type Express, type Request, type Response, type NextFunction } from 'express';
const app: Express = express();
app.use(express.json()); // for parsing application/jsonapp.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', function (req: Request, res: Response, next: NextFunction) { console.log(req.body); res.json(req.body);});req.cookies
在使用 cookie-parser 中间件时,该属性是一个包含请求发送的 cookie 的对象。如果请求不包含任何 cookie,则默认为 {}。
🌐 When using cookie-parser middleware, this property is an object that
contains cookies sent by the request. If the request contains no cookies, it defaults to {}.
// Cookie: name=tjconsole.dir(req.cookies.name);// => 'tj'如果 cookie 已经被签名,你必须使用 req.signedCookies。
🌐 If the cookie has been signed, you have to use req.signedCookies.
有关更多信息、问题或疑虑,请参见 cookie-parser。
🌐 For more information, issues, or concerns, see cookie-parser.
req.fresh
当响应在客户端缓存中仍然“新鲜”时,返回 true,否则返回 false,以表明客户端缓存现在已过期,应发送完整响应。
🌐 When the response is still “fresh” in the client’s cache true is returned, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent.
当客户端发送 Cache-Control: no-cache 请求头以指示端到端重新加载请求时,该模块将返回 false,以使处理这些请求变得透明。
🌐 When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent.
有关缓存验证如何工作的更多详细信息,请参阅 HTTP/1.1 缓存规范。
🌐 Further details for how cache validation works can be found in the HTTP/1.1 Caching Specification.
console.dir(req.fresh);// => truereq.hostname
包含从 Host HTTP 头派生的主机名。
🌐 Contains the hostname derived from the Host HTTP header.
当 trust proxy 设置 不等于 false 时,此属性将改为从 X-Forwarded-Host 头字段获取值。该头可以由客户端或代理设置。
🌐 When the trust proxy setting
does not evaluate to false, this property will instead get the value
from the X-Forwarded-Host header field. This header can be set by
the client or by the proxy.
如果请求中有多个 X-Forwarded-Host 头,则使用第一个头的值。这包括带有逗号分隔值的单个头,其中使用第一个值。
🌐 If there is more than one X-Forwarded-Host header in the request, the
value of the first header is used. This includes a single header with
comma-separated values, in which the first value is used.
Note
在 Express v4.17.0 之前,X-Forwarded-Host 不能包含多个值,也不能出现多次。
🌐 Prior to Express v4.17.0, the X-Forwarded-Host could not contain multiple values or be present
more than once.
// Host: "example.com:3000"console.dir(req.hostname);// => 'example.com'req.host
Caution
req.host 是 req.hostname 的一个过时别名,返回相同的值——即去掉端口号的主机名。从 Express v4.5.0 开始,它会发出弃用警告。请改用 req.hostname。
// Host: "example.com:3000"console.dir(req.host);// => 'example.com'req.ip
包含请求的远程 IP 地址。
🌐 Contains the remote IP address of the request.
当 trust proxy 设置 不等于 false 时,该属性的值由 X-Forwarded-For 头中最左边的条目得出。该头可以由客户端或代理设置。
🌐 When the trust proxy setting does not evaluate to false,
the value of this property is derived from the left-most entry in the
X-Forwarded-For header. This header can be set by the client or by the proxy.
console.dir(req.ip);// => '127.0.0.1'req.ips
当 trust proxy 设置 不等于 false 时,该属性包含在 X-Forwarded-For 请求头中指定的 IP 地址数组。否则,它包含一个空数组。该请求头可以由客户端或代理设置。
🌐 When the trust proxy setting does not evaluate to false,
this property contains an array of IP addresses
specified in the X-Forwarded-For request header. Otherwise, it contains an
empty array. This header can be set by the client or by the proxy.
例如,如果 X-Forwarded-For 是 client, proxy1, proxy2,req.ips 将是 ["client", "proxy1", "proxy2"],其中 proxy2 是最下游的。
🌐 For example, if X-Forwarded-For is client, proxy1, proxy2, req.ips would be
["client", "proxy1", "proxy2"], where proxy2 is the furthest downstream.
// normal request, or `trust proxy` disabled (the default)console.dir(req.ips);// => []
// app.set('trust proxy', true) and// request header `X-Forwarded-For: client, proxy1, proxy2`console.dir(req.ips);// => ['client', 'proxy1', 'proxy2']req.method
包含一个对应于请求的HTTP方法的字符串:
GET、POST、PUT,依此类推。
🌐 Contains a string corresponding to the HTTP method of the request:
GET, POST, PUT, and so on.
app.use(function (req, res, next) { console.dir(req.method); // => 'GET' next();});import { type Request, type Response, type NextFunction } from 'express';
app.use(function (req: Request, res: Response, next: NextFunction) { console.dir(req.method); // => 'GET' next();});req.originalUrl
Caution
req.url 不是 Express 的原生属性,它是继承自 Node 的 http 模块。
此属性类似于 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=somethingconsole.dir(req.originalUrl);// => '/search?q=something'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();});import { type Request, type Response, type NextFunction } from 'express';
app.use('/admin', function (req: Request, res: Response, next: NextFunction) { // 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
该属性是一个对象,包含映射到命名路由“参数”的属性。例如,如果你有路由 /user/:name,那么“name”属性可以作为 req.params.name 使用。该对象的默认值为 {}。
🌐 This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.
// GET /user/tjconsole.dir(req.params.name);// => 'tj'当你在路由定义中使用正则表达式时,捕获组会作为整数键提供,使用 req.params[n],其中 n 是第 n个 捕获组。此规则适用于使用字符串路由的未命名通配符匹配,例如 /file/*:
// GET /file/javascripts/jquery.jsconsole.dir(req.params[0]);// => 'javascripts/jquery.js'正则表达式中的命名捕获组的行为类似于命名路由参数。例如,来自 /^\/file\/(?<path>.*)$/ 表达式的组可以作为 req.params.path 使用。
如果你需要更改 req.params 中的某个键,请使用 app.param 处理程序。更改仅适用于路由路径中已定义的 参数。
🌐 If you need to make changes to a key in req.params, use the app.param handler. Changes are applicable only to parameters already defined in the route path.
在中间件或路由处理程序中对 req.params 对象所做的任何更改都将被重置。
🌐 Any changes made to the req.params object in a middleware or route handler will be reset.
Note
Express 会自动解码 req.params 中的值(使用 decodeURIComponent)。
🌐 Express automatically decodes the values in req.params (using decodeURIComponent).
req.path
包含请求 URL 的路径部分。
🌐 Contains the path part of the request URL.
// example.com/users?sort=descconsole.dir(req.path);// => '/users'Note
req.protocol
包含请求协议字符串:要么是 http,要么是(对于 TLS 请求)https。
🌐 Contains the request protocol string: either http or (for TLS requests) https.
当 trust proxy 设置 不等于 false 时,如果存在,属性将使用 X-Forwarded-Proto 头字段的值。该头字段可以由客户端或代理设置。
🌐 When the trust proxy setting does not evaluate to false,
this property will use the value of the X-Forwarded-Proto header field if present.
This header can be set by the client or by the proxy.
console.dir(req.protocol);// => 'http'req.query
此属性是一个对象,其中包含路由中每个查询字符串参数的属性。当查询解析器设置为禁用时,它是一个空对象 {},否则它是配置的查询解析器的结果。
🌐 This property is an object containing a property for each query string parameter in the route.
When query parser is set to disabled, it is an empty object {}, otherwise it is the result of the configured query parser.
Warning
由于 req.query 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.query.foo.toString() 可能会以多种方式失败,例如 foo 可能不存在或可能不是字符串,而 toString 可能不是函数,而是字符串或其他用户输入。
🌐 As req.query’s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, req.query.foo.toString() may
fail in multiple ways, for example foo may not be there or may not be a string, and toString
may not be a function and instead a string or other user-input.
此属性的值可以通过查询解析器应用设置进行配置,以满足你的应用需求。一个非常流行的查询字符串解析器是qs模块,它是默认使用的。qs模块具有许多可配置的设置,可能希望使用不同于默认的设置来填充req.query:
🌐 The value of this property can be configured with the query parser application setting to work how your application needs it. A very popular query string parser is the qs module, and this is used by default. The qs module is very configurable with many settings, and it may be desirable to use different settings than the default to populate req.query:
var qs = require('qs');app.set('query parser', function (str) { return qs.parse(str, { /* custom options */ });});import qs from 'qs';
app.set('query parser', function (str) { return qs.parse(str, { /* custom options */ });});import qs from 'qs';
app.set('query parser', function (str: string) { 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.
app.get('/', function (req, res) { console.dir(req.res === res); // => true res.send('OK');});import { type Request, type Response } from 'express';
app.get('/', function (req: Request, res: Response) { console.dir(req.res === res); // => true res.send('OK');});req.route
包含当前匹配的路由(一个 Route 对象)。例如:
🌐 Contains the currently-matched route (a Route object). For example:
app.get('/user/:id?', function userIdHandler(req, res) { console.log(req.route); res.send('GET');});import { type Request, type Response } from 'express';
app.get('/user/:id?', function userIdHandler(req: Request, res: Response) { console.log(req.route); res.send('GET');});前一个代码片段的示例输出:
🌐 Example output from the previous snippet:
{ path: '/user/:id?', stack: [ { handle: [Function: userIdHandler], name: 'userIdHandler', params: undefined, path: undefined, keys: [], regexp: /^\/?$/i, method: 'get' } ], methods: { get: true } }req.secure
如果建立了 TLS 连接,则布尔属性为真。等同于:
🌐 A Boolean property that is true if a TLS connection is established. Equivalent to:
console.dir(req.protocol === 'https');// => truereq.signedCookies
在使用 cookie-parser 中间件时,该属性包含请求发送的已签名 cookie,未签名并可直接使用。已签名的 cookie 存放在不同的对象中,以显示开发者的意图;否则,恶意攻击可能会针对 req.cookie 值(这些值很容易被伪造)。注意,签名 cookie 并不会使其“隐藏”或加密,只是简单地防止篡改(因为用于签名的密钥是私有的)。
🌐 When using cookie-parser middleware, this property
contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside
in a different object to show developer intent; otherwise, a malicious attack could be placed on
req.cookie values (which are easy to spoof). Note that signing a cookie does not make it “hidden”
or encrypted; but simply prevents tampering (because the secret used to sign is private).
如果未发送已签名的 cookie,该属性默认值为 {}。
🌐 If no signed cookies are sent, the property defaults to {}.
// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3console.dir(req.signedCookies.user);// => 'tobi'有关更多信息、问题或疑虑,请参见 cookie-parser。
🌐 For more information, issues, or concerns, see cookie-parser.
req.stale
指示请求是否为“陈旧”,并且与 req.fresh 相反。有关更多信息,请参见 req.fresh。
🌐 Indicates whether the request is “stale,” and is the opposite of req.fresh.
For more information, see req.fresh.
console.dir(req.stale);// => truereq.subdomains
请求的域名中的子域数组。
🌐 An array of subdomains in the domain name of the request.
// Host: "tobi.ferrets.example.com"console.dir(req.subdomains);// => ['ferrets', 'tobi']应用属性 subdomain offset,默认值为 2,用于确定子域段的起始位置。要更改此行为,请使用 app.set 修改其值。
🌐 The application property subdomain offset, which defaults to 2, is used for determining the
beginning of the subdomain segments. To change this behavior, change its value
using app.set.
req.xhr
一个布尔属性,如果请求的 X-Requested-With 头字段是 “XMLHttpRequest”,则为 true,表示该请求是由 jQuery 等客户端库发出的。
🌐 A Boolean property that is true if the request’s X-Requested-With header field is
“XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.
console.dir(req.xhr);// => true方法
🌐 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()
Arguments
types要检查的内容类型:一种 MIME 类型(例如 application/json)、扩展名(例如 json)、逗号分隔的列表或数组。
根据请求的 Accept HTTP 头字段,检查指定的内容类型是否可接受。该方法返回最佳匹配,如果没有任何指定的内容类型可接受,则返回 false(在这种情况下,应用应响应 406 "Not Acceptable")。
🌐 Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field.
The method returns the best match, or if none of the specified content types is acceptable, returns
false (in which case, the application should respond with 406 "Not Acceptable").
type 值可以是单个 MIME 类型字符串(例如 “application/json”)、扩展名(例如 “json”)、逗号分隔的列表或数组。对于列表或数组,该方法返回 最佳 匹配(如果有)。
🌐 The type value may be a single MIME type string (such as “application/json”),
an extension name such as “json”, a comma-delimited list, or an array. For a
list or array, the method returns the best match (if any).
// Accept: text/htmlreq.accepts('html');// => "html"
// Accept: text/*, application/jsonreq.accepts('html');// => "html"req.accepts('text/html');// => "text/html"req.accepts(['json', 'text']);// => "json"req.accepts('application/json');// => "application/json"
// Accept: text/*, application/jsonreq.accepts('image/png');req.accepts('png');// => false
// Accept: text/*;q=.5, application/jsonreq.accepts(['html', 'json']);// => "json"如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts。
🌐 For more information, or if you have issues or concerns, see accepts.
req.acceptsCharsets()
Arguments
charset一个或多个字符集,用于测试请求的 Accept-Charset 头。
根据请求的 Accept-Charset HTTP 头字段,返回指定字符集中的第一个被接受的字符集。如果没有任何指定的字符集被接受,则返回 false。
🌐 Returns the first accepted charset of the specified character sets,
based on the request’s Accept-Charset HTTP header field.
If none of the specified charsets is accepted, returns false.
// Accept-Charset: utf-8, iso-8859-1;q=0.5req.acceptsCharsets('utf-8', 'iso-8859-1');// => 'utf-8'
req.acceptsCharsets('us-ascii');// => false如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts。
🌐 For more information, or if you have issues or concerns, see accepts.
req.acceptsCharset()
Arguments
charset一个或多个字符集,用于测试请求的 Accept-Charset 头。
Caution
req.acceptsCharset() 是 req.acceptsCharsets() 的单数别名,行为完全相同。自 Express v4.5.0 起,它已发出弃用警告。请改用 req.acceptsCharsets()。
你可以使用以下代码转换自动更新你的代码:
🌐 You can update your code automatically with the following codemod:
npx codemod@latest @expressjs/pluralize-method-namesyarn dlx codemod@latest @expressjs/pluralize-method-namespnpm dlx codemod@latest @expressjs/pluralize-method-namesbunx codemod@latest @expressjs/pluralize-method-namesreq.acceptsEncodings()
Arguments
encoding一个或多个编码,用于测试请求的 Accept-Encoding 头。
根据请求的 Accept-Encoding HTTP 头字段,返回指定编码中第一个被接受的编码。如果没有指定的编码被接受,则返回 false。
🌐 Returns the first accepted encoding of the specified encodings,
based on the request’s Accept-Encoding HTTP header field.
If none of the specified encodings is accepted, returns false.
// Accept-Encoding: gzip, deflatereq.acceptsEncodings('gzip', 'deflate');// => 'gzip'
req.acceptsEncodings('br');// => false如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts。
🌐 For more information, or if you have issues or concerns, see accepts.
req.acceptsEncoding()
Arguments
encoding一个或多个编码,用于测试请求的 Accept-Encoding 头。
Caution
req.acceptsEncoding() 是 req.acceptsEncodings() 的单数别名,行为完全相同。自 Express v4.5.0 起,它已发出弃用警告。请改用 req.acceptsEncodings()。
你可以使用以下代码转换自动更新你的代码:
🌐 You can update your code automatically with the following codemod:
npx codemod@latest @expressjs/pluralize-method-namesyarn dlx codemod@latest @expressjs/pluralize-method-namespnpm dlx codemod@latest @expressjs/pluralize-method-namesbunx codemod@latest @expressjs/pluralize-method-namesreq.acceptsLanguages()
Arguments
lang一个或多个用于测试请求的 Accept-Language 头的语言。如果省略,将以数组形式返回所有接受的语言。
根据请求的 Accept-Language HTTP 头字段,返回指定语言中第一个被接受的语言。如果没有指定的语言被接受,则返回 false。
🌐 Returns the first accepted language of the specified languages,
based on the request’s Accept-Language HTTP header field.
If none of the specified languages is accepted, returns false.
如果没有提供 lang 参数,那么 req.acceptsLanguages() 会将 HTTP Accept-Language 头中的所有语言作为 Array 返回。
🌐 If no lang argument is given, then req.acceptsLanguages()
returns all languages from the HTTP Accept-Language header
as an Array.
// Accept-Language: en;q=0.8, esreq.acceptsLanguages('en', 'es');// => 'es'
req.acceptsLanguages();// => ['es', 'en']如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts。
🌐 For more information, or if you have issues or concerns, see accepts.
req.acceptsLanguage()
Arguments
lang一个或多个用于测试请求的 Accept-Language 头的语言。如果省略,将以数组形式返回所有接受的语言。
Caution
req.acceptsLanguage() 是 req.acceptsLanguages() 的单数别名,行为完全相同。自 Express v4.5.0 起,它已发出弃用警告。请改用 req.acceptsLanguages()。
你可以使用以下代码转换自动更新你的代码:
🌐 You can update your code automatically with the following codemod:
npx codemod@latest @expressjs/pluralize-method-namesyarn dlx codemod@latest @expressjs/pluralize-method-namespnpm dlx codemod@latest @expressjs/pluralize-method-namesbunx codemod@latest @expressjs/pluralize-method-namesExpress (4.x) 源码: request.js 第179行
🌐 Express (4.x) source: request.js line 179
接受 (1.3) 来源: index.js 第195行
🌐 Accepts (1.3) source: index.js line 195
req.get()
Arguments
field要读取的 HTTP 请求头的名称(不区分大小写)。Referrer 和 Referer 可以互换使用。
返回指定的 HTTP 请求头字段(大小写不敏感匹配)。
Referrer 和 Referer 字段可以互换。
🌐 Returns the specified HTTP request header field (case-insensitive match).
The Referrer and Referer fields are interchangeable.
req.get('Content-Type');// => "text/plain"
req.get('content-type');// => "text/plain"
req.get('Something');// => undefined别名为 req.header(field)。
🌐 Aliased as req.header(field).
req.is()
Arguments
type要与请求的 Content-Type 头匹配的 MIME 类型或扩展名。
如果传入请求的 “Content-Type” HTTP 头字段与 type 参数指定的 MIME 类型匹配,则返回匹配的内容类型。如果请求没有正文,则返回 null。否则返回 false。
🌐 Returns the matching content type if the incoming request’s “Content-Type” HTTP header field
matches the MIME type specified by the type parameter. If the request has no body, returns null.
Returns false otherwise.
// With Content-Type: text/html; charset=utf-8req.is('html');// => 'html'req.is('text/html');// => 'text/html'req.is('text/*');// => 'text/*'
// When Content-Type is application/jsonreq.is('json');// => 'json'req.is('application/json');// => 'application/json'req.is('application/*');// => 'application/*'
// Using arrays// When Content-Type is application/jsonreq.is(['json', 'html']);// => 'json'
// Using multiple arguments// When Content-Type is application/jsonreq.is('json', 'html');// => 'json'
req.is('html');// => falsereq.is(['xml', 'yaml']);// => falsereq.is('xml', 'yaml');// => false欲了解更多信息,或如果你有任何问题或顾虑,请参阅type-is。
🌐 For more information, or if you have issues or concerns, see type-is.
req.param()
Arguments
name要查找的参数名称,先在 req.params 中搜索,然后是 req.body,最后是 req.query。
defaultValue当在任何请求对象中找不到该参数时要返回的值。
Caution
已弃用。请根据情况使用 req.params、req.body 或 req.query。
🌐 Deprecated. Use either req.params, req.body or req.query, as applicable.
当存在时,返回参数 name 的值。
🌐 Returns the value of param name when present.
// ?name=tobireq.param('name');// => "tobi"
// POST name=tobireq.param('name');// => "tobi"
// /user/tobi for /user/:namereq.param('name');// => "tobi"查找按以下顺序进行:
🌐 Lookup is performed in the following order:
req.paramsreq.bodyreq.query
可选地,你可以指定 defaultValue 来设置默认值,如果在任何请求对象中都没有找到该参数。
🌐 Optionally, you can specify defaultValue to set a default value if the parameter is not found in any of the request objects.
Warning
为了清晰起见,应优先直接访问 req.body、req.params 和 req.query——除非你确实接受每个对象的输入。
🌐 Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
必须加载请求体解析中间件才能使 req.param() 可预测地工作。详情请参阅 req.body。
🌐 Body-parsing middleware must be loaded for req.param() to work predictably. Refer req.body for details.
req.range()
Arguments
size资源的最大大小。
options解析 Range 头的选项。
combine指定是否应合并重叠和相邻的范围。当 true 时,范围会被合并并作为在头部中以这种方式指定的返回。
Range 头部解析器。
将返回一个范围数组,或者返回表示解析错误的负数。
🌐 An array of ranges will be returned or negative numbers indicating an error parsing.
-2表示标头字符串格式错误-1发出不可满足范围的信号
// parse header from requestvar range = req.range(1000);
// the type of the rangeif (range.type === 'bytes') { // the ranges range.forEach(function (r) { // do something with r.start and r.end });}