Skip to main content

Route

每当使用 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 before v1.9 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.

返回

¥Returns


continue

Added before v1.9 route.continue

使用可选覆盖将路由的请求发送到网络。

¥Sends route's request to the network 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.

返回

¥Returns

细节

¥Details

headers 选项适用于路由请求及其发起的任何重定向。但是,urlmethodpostData 仅适用于原始请求,不会延续到重定向请求。

¥The headers option applies to both the routed request and any redirects it initiates. However, url, method, and postData only apply to the original request and are not carried over to redirected requests.

route.continue() 将立即将请求发送到网络,不会调用其他匹配的处理程序。如果你希望调用链中的下一个匹配处理程序,请使用 route.fallback()

¥route.continue() will immediately send the request to the network, other matching handlers won't be invoked. Use route.fallback() If you want next matching handler in the chain to be invoked.


fallback

Added in: v1.23 route.fallback

通过可选覆盖继续路由的请求。该方法类似于 route.continue(),不同之处在于在发送请求之前将调用其他匹配的处理程序。

¥Continues route's request with optional overrides. The method is similar to route.continue() with the difference that other matching handlers will be invoked before sending the request.

用法

¥Usage

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

¥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.

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 });
});

使用 route.continue() 立即将请求发送到网络,在这种情况下不会调用其他匹配的处理程序。

¥Use route.continue() to immediately send the request to the network, other matching handlers won't be invoked in that case.

参数

¥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.

返回

¥Returns


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.

  • maxRetries number (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

如果设置更改请求方法(例如 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 before v1.9 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.

返回

¥Returns


request

Added before v1.9 route.request

要路由的请求。

¥A request to be routed.

用法

¥Usage

route.request();

返回

¥Returns