Skip to main content

路由

每当使用 page.route()browserContext.route() 设置网络路由时,Route 对象就允许处理该路由。

Whenever a network route is set up with page.route() or browserContext.route(), the Route object allows to handle the route.

了解有关 networking 的更多信息。

Learn more about networking.


方法

Methods

abort

Added in: v1.8 route.abort

中止路由的请求。

Aborts the route's request.

用法

Usage

await route.abort();
await route.abort(errorCode);

参数

Arguments

可选错误代码。默认为 failed,可以是以下之一:

Optional error code. Defaults to failed, could be one of the following:

  • 'aborted' - 操作被中止(由于用户操作)

    'aborted' - An operation was aborted (due to user action)

  • 'accessdenied' - 访问网络以外的资源的权限被拒绝

    'accessdenied' - Permission to access a resource, other than the network, was denied

  • 'addressunreachable' - IP 地址不可达。这通常意味着没有到指定主机或网络的路由。

    'addressunreachable' - The IP address is unreachable. This usually means that there is no route to the specified host or network.

  • 'blockedbyclient' - 客户端选择阻止该请求。

    'blockedbyclient' - The client chose to block the request.

  • 'blockedbyresponse' - 请求失败,因为响应是随未满足的要求一起传递的(例如 'X 框架选项' 和 '内容安全策略' 祖级检查)。

    'blockedbyresponse' - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).

  • 'connectionaborted' - 由于未收到已发送数据的 ACK,连接超时。

    'connectionaborted' - A connection timed out as a result of not receiving an ACK for data sent.

  • 'connectionclosed' - 连接已关闭(对应于 TCP FIN)。

    'connectionclosed' - A connection was closed (corresponding to a TCP FIN).

  • 'connectionfailed' - 连接尝试失败。

    'connectionfailed' - A connection attempt failed.

  • 'connectionrefused' - 连接尝试被拒绝。

    'connectionrefused' - A connection attempt was refused.

  • 'connectionreset' - 连接已重置(对应于 TCP RST)。

    'connectionreset' - A connection was reset (corresponding to a TCP RST).

  • 'internetdisconnected' - 互联网连接已丢失。

    'internetdisconnected' - The Internet connection has been lost.

  • 'namenotresolved' - 无法解析主机名。

    'namenotresolved' - The host name could not be resolved.

  • 'timedout' - 操作超时。

    'timedout' - An operation timed out.

  • 'failed' - 发生一般性故障。

    'failed' - A generic failure occurred.


continue

Added in: v1.8 route.continue

通过可选覆盖继续路由的请求。

Continues route's request with optional overrides.

用法

Usage

await page.route('**/*', async (route, request) => {
// Override headers
const headers = {
...request.headers(),
foo: 'foo-value', // set "foo" header
bar: undefined, // remove "bar" header
};
await route.continue({ headers });
});

参数

Arguments

如果设置更改请求 HTTP 标头。标头值将转换为字符串。

If set changes the request HTTP headers. Header values will be converted to a string.

如果设置更改请求方法(例如 GET 或 POST)。

If set changes the request method (e.g. GET or POST).

如果设置更改请求的发布数据。

If set changes the post data of request.

如果设置更改请求 URL。新 URL 必须与原始 URL 具有相同的协议。

If set changes the request URL. New URL must have same protocol as original one.

细节

Details

请注意,任何覆盖(例如 urlheaders)仅适用于正在路由的请求。如果此请求导致重定向,则覆盖将不会应用于新的重定向请求。如果你想通过重定向传播标头,请使用 route.fetch()route.fulfill() 的组合。

Note that any overrides such as url or headers only apply to the request being routed. If this request results in a redirect, overrides will not be applied to the new redirected request. If you want to propagate a header through redirects, use the combination of route.fetch() and route.fulfill() instead.


fallback

Added in: v1.23 route.fallback

当多个路由与给定模式匹配时,它们将按照与其注册相反的顺序运行。这样,最后注册的路由总是可以覆盖所有先前的路由。在下面的示例中,请求将首先由最底层的处理程序处理,然后它将回退到前一个处理程序,最后将被第一个注册的路由中止。

When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first registered route.

用法

Usage

await page.route('**/*', async route => {
// Runs last.
await route.abort();
});
await page.route('**/*', async route => {
// Runs second.
await route.fallback();
});
await page.route('**/*', async route => {
// Runs first.
await route.fallback();
});

当你希望单独的处理程序处理不同类型的请求时,注册多个路由非常有用,例如 API 调用与页面资源或 GET 请求与 POST 请求(如下例所示)。

Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example API calls vs page resources or GET requests vs POST requests as in the example below.

// Handle GET requests.
await page.route('**/*', async route => {
if (route.request().method() !== 'GET') {
await route.fallback();
return;
}
// Handling GET only.
// ...
});

// Handle POST requests.
await page.route('**/*', async route => {
if (route.request().method() !== 'POST') {
await route.fallback();
return;
}
// Handling POST only.
// ...
});

我们还可以在回退到后续处理程序时修改请求,这样中间路由处理程序就可以修改请求的 url、方法、标头和 postData。

One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request.

await page.route('**/*', async (route, request) => {
// Override headers
const headers = {
...request.headers(),
foo: 'foo-value', // set "foo" header
bar: undefined, // remove "bar" header
};
await route.fallback({ headers });
});

参数

Arguments

如果设置更改请求 HTTP 标头。标头值将转换为字符串。

If set changes the request HTTP headers. Header values will be converted to a string.

如果设置更改请求方法(例如 GET 或 POST)。

If set changes the request method (e.g. GET or POST).

如果设置更改请求的发布数据。

If set changes the post data of request.

如果设置更改请求 URL。新 URL 必须与原始 URL 具有相同的协议。更改 URL 不会影响路由匹配,所有路由均使用原始请求 URL 进行匹配。

If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route matching, all the routes are matched using the original request URL.


fetch

Added in: v1.29 route.fetch

执行请求并获取结果而不执行它,以便可以修改响应然后执行。

Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.

用法

Usage

await page.route('https://dog.ceo/api/breeds/list/all', async route => {
const response = await route.fetch();
const json = await response.json();
json.message['big_red_dog'] = [];
await route.fulfill({ response, json });
});

参数

Arguments

如果设置更改请求 HTTP 标头。标头值将转换为字符串。

If set changes the request HTTP headers. Header values will be converted to a string.

  • maxRedirects number (optional) Added in: v1.31#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

如果设置更改请求方法(例如 GET 或 POST)。

If set changes the request method (e.g. GET or POST).

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • timeout number (optional) Added in: v1.33#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

如果设置更改请求 URL。新 URL 必须与原始 URL 具有相同的协议。

If set changes the request URL. New URL must have same protocol as original one.

返回

Returns

细节

Details

请注意,headers 选项将应用于获取的请求以及由它发起的任何重定向。如果你只想将 headers 应用于原始请求,而不应用于重定向,请改为查看 route.continue()

Note that headers option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply headers to the original request, but not to redirects, look into route.continue() instead.


fulfill

Added in: v1.8 route.fulfill

通过给定的响应来满足路由的请求。

Fulfills route's request with given response.

用法

Usage

使用 404 响应满足所有请求的示例:

An example of fulfilling all requests with 404 responses:

await page.route('**/*', async route => {
await route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!'
});
});

提供静态文件的示例:

An example of serving static file:

await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));

参数

Arguments

响应体。

Response body.

如果设置,则等于设置 Content-Type 响应头。

If set, equals to setting Content-Type response header.

响应标头。标头值将转换为字符串。

Response headers. Header values will be converted to a string.

JSON 响应。如果未设置,此方法会将内容类型设置为 application/json

JSON response. This method will set the content type to application/json if not set.

用于响应的文件路径。内容类型将从文件扩展名推断出来。如果 path 是相对路径,则相对于当前工作目录进行解析。

File path to respond with. The content type will be inferred from file extension. If path is a relative path, then it is resolved relative to the current working directory.

APIResponse 来满足路由的请求。可以使用完成选项覆盖响应的各个字段(例如标头)。

APIResponse to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.

响应状态码,默认为 200

Response status code, defaults to 200.


request

Added in: v1.8 route.request

要路由的请求。

A request to be routed.

用法

Usage

route.request();

返回

Returns