🌐 Nodejs.cn

请求对象

req 对象表示 HTTP 请求,并具有请求查询字符串、参数、正文、HTTP 头等属性。在本指南中,并且按照惯例,该对象总是被称为 req(HTTP 响应则为 res),但它的实际名称取决于你正在使用的回调函数的参数。

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

例如:

🌐 For example:

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

但你同样可以有:

🌐 But you could just as well have:

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

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

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

属性

🌐 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.app

此属性保存对正在使用该中间件的 Express 应用实例的引用。

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

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

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

例如:

🌐 For example:

index.cjs
app.get('/viewdirectory', require('./mymiddleware.cjs'));

而中间件模块本身:

🌐 And the middleware module itself:

mymiddleware.cjs
module.exports = (req, res) => {
res.send(`The views directory is ${req.app.get('views')}`);
};

req.baseUrl

路由实例挂载的 URL 路径。

🌐 The URL path on which a router instance was mounted.

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

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

例如:

🌐 For example:

const greet = express.Router();
greet.get('/jp', (req, res) => {
console.log(req.baseUrl); // /greet
res.send('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:"param"t', '/hel{l}o'], greet); // load the router on '/gre:"param"t' and '/hel{l}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.

index.cjs
const express = require('express');
const app = express();
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', (req, res, next) => {
console.log(req.body);
res.json(req.body);
});

req.cookies

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

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

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

如果 cookie 已经被签名,你必须使用 req.signedCookies

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

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

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

req.fresh

当响应在客户端缓存中仍然“新鲜”时,返回 true,否则返回 false,以表明客户端缓存现在已过期,应发送完整响应。

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

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

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

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

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

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

req.host

包含来源于 Host HTTP 头的主机。

🌐 Contains the host derived from the Host HTTP header.

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

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

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

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

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

req.hostname

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

🌐 Contains the hostname derived from the Host HTTP header.

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

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

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

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

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

req.ip

包含请求的远程 IP 地址。

🌐 Contains the remote IP address of the request.

trust proxy 设置 不等于 false 时,该属性的值由 X-Forwarded-For 头中最左边的条目得出。该头可以由客户端或代理设置。

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

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

req.ips

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

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

例如,如果 X-Forwarded-Forclient, proxy1, proxy2req.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方法的字符串: GETPOSTPUT,依此类推。

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

app.use((req, res, next) => {
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=something
console.dir(req.originalUrl);
// => "/search?q=something"

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

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

req.params

此属性是一个对象,包含映射到 命名路由“参数” 的属性。例如,如果你有路由 /user/:name,那么 “name” 属性可以作为 req.params.name 使用。当使用字符串路径时,该对象默认为 Object.create(null),但当路径定义为正则表达式时,它仍然是一个具有普通原型的标准对象。

🌐 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 Object.create(null) when using string paths, but remains a standard object with a normal prototype when the path is defined with a regular expression.

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

对应通配符参数的属性是包含按 / 分割的独立路径段的数组:

🌐 Properties corresponding to wildcard parameters are arrays containing separate path segments split on /:

app.get('/files/*file', (req, res) => {
console.dir(req.params.file);
// GET /files/note.txt
// => [ 'note.txt' ]
// GET /files/images/image.png
// => [ 'images', 'image.png' ]
});

当你在路由定义中使用正则表达式时,捕获组会以整数键 req.params[n] 提供,其中 n 是第 n 捕获组。

app.use(/^\/file\/(.*)$/, (req, res) => {
// GET /file/javascripts/jquery.js
console.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=desc
console.dir(req.path);
// => "/users"

Note

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

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

req.protocol

包含请求协议字符串:要么是 http,要么是(对于 TLS 请求)https

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

trust proxy 设置 不等于 false 时,如果存在,属性将使用 X-Forwarded-Proto 头字段的值。该头字段可以由客户端或代理设置。

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

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

req.query

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

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

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:

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

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

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

req.res

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

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

app.get('/', (req, res) => {
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}', (req, res) => {
console.dir(req.route, { depth: null });
res.send('GET');
});

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

🌐 Example output from the previous snippet:

Route {
path: '/user/{:id}',
stack: [
Layer {
handle: [Function (anonymous)],
keys: [],
name: '<anonymous>',
params: undefined,
path: undefined,
slash: false,
matchers: [ [Function: match] ],
method: 'get'
}
],
methods: [Object: null prototype] { get: true }
}

req.secure

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

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

req.protocol === 'https';

req.signedCookies

在使用 cookie-parser 中间件时,该属性包含请求发送的已签名 cookie,未签名并可直接使用。已签名的 cookie 存放在不同的对象中,以显示开发者的意图;否则,恶意攻击可能会针对 req.cookie 值(这些值很容易被伪造)。注意,签名 cookie 并不会使其“隐藏”或加密,只是简单地防止篡改(因为用于签名的密钥是私有的)。

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

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

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

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

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

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

req.stale

指示请求是否为“陈旧”,并且与 req.fresh 相反。有关更多信息,请参见 req.fresh

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

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

req.subdomains

请求的域名中的子域数组。

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

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

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

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

req.xhr

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

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

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

方法

🌐 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
Type:String | String[]

要检查的内容类型:一种 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/html
req.accepts('html');
// => "html"
// Accept: text/*, application/json
req.accepts('html');
// => "html"
req.accepts('text/html');
// => "text/html"
req.accepts(['json', 'text']);
// => "json"
req.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
req.accepts('image/png');
req.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
// => "json"

如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts

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

req.acceptsCharsets()

Arguments

charset
Type:String | String[]

一个或多个字符集,用于测试请求的 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.5
req.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.acceptsEncodings()

Arguments

encoding
Type:String | String[]

一个或多个编码,用于测试请求的 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, deflate
req.acceptsEncodings('gzip', 'deflate');
// => 'gzip'
req.acceptsEncodings('br');
// => false

如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts

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

req.acceptsLanguages()

Arguments

lang
Type:String | String[] | undefined

一个或多个用于测试请求的 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, es
req.acceptsLanguages('en', 'es');
// => 'es'
req.acceptsLanguages();
// => ['es', 'en']

如需更多信息,或如果你有任何问题或顾虑,请参阅 accepts

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

Express (5.x) 源码: request.js 第172行

🌐 Express (5.x) source: request.js line 172

接受 (2.0) 来源: index.js 第195行

🌐 Accepts (2.0) source: index.js line 195

req.get()

Arguments

field
Type:String

要读取的 HTTP 请求头的名称(不区分大小写)。ReferrerReferer 可以互换使用。

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

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

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

别名为 req.header(field)

🌐 Aliased as req.header(field).

req.is()

Arguments

type
Type:String | String[]

要与请求的 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-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

欲了解更多信息,或如果你有任何问题或顾虑,请参阅type-is

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

req.range()

Arguments

size
Type:Number

资源的最大大小。

options
Type:Object | undefined

解析 Range 头的选项。

combine
Type:BooleanDefault:false

指定是否应合并重叠和相邻的范围。当 true 时,范围会被合并并作为在头部中以这种方式指定的返回。

Range 头部解析器。

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

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

  • -2 表示标头字符串格式错误
  • -1 发出不可满足范围的信号
// parse header from request
const range = req.range(1000);
// the type of the range
if (range.type === 'bytes') {
// the ranges
range.forEach((r) => {
// do something with r.start and r.end
});
}