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.

了解更多关于网络的信息。

🌐 Learn more about networking.


方法

🌐 Methods

abort

Added before v1.9 route.abort

中止路由的请求。

🌐 Aborts the route's request.

用法

Route.abort();
Route.abort(errorCode);

参数

  • errorCode String (optional)#

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

    • 'aborted' - 操作已中止(由于用户操作)
    • 'accessdenied' - 访问资源(网络除外)的权限被拒绝
    • 'addressunreachable' - 该 IP 地址无法访问。这通常意味着没有通往指定主机或网络的路由。
    • 'blockedbyclient' - 客户端选择了阻止请求。
    • 'blockedbyresponse' - 请求失败,因为响应在附带不满足的要求的情况下被传送(例如 'X-Frame-Options' 和 'Content-Security-Policy' 的祖级检查)。
    • 'connectionaborted' - 由于未收到已发送数据的确认,应答(ACK),连接超时。
    • 'connectionclosed' - 一个连接已关闭(对应 TCP 的 FIN)。
    • 'connectionfailed' - 连接尝试失败。
    • 'connectionrefused' - 连接尝试被拒绝。
    • 'connectionreset' - 连接被重置(对应于 TCP RST)。
    • 'internetdisconnected' - 网络连接已断开。
    • 'namenotresolved' - 无法解析主机名称。
    • 'timedout' - 操作超时。
    • 'failed' - 发生了一般性故障。

返回


fallback

Added in: v1.23 route.fallback

继续路由的请求,并可选择性地覆盖。该方法类似于 Route.resume(),不同之处在于会在发送请求之前调用其他匹配的处理程序。

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

用法

当多个路由匹配给定的模式时,它们会按与注册顺序相反的顺序运行。这样,最后注册的路由总是可以覆盖之前的所有路由。在下面的例子中,请求将首先由最底部的处理器处理,然后回退到之前的处理器,最终会被最先注册的路由中断。

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

page.route("**/*", route -> {
// Runs last.
route.abort();
});

page.route("**/*", route -> {
// Runs second.
route.fallback();
});

page.route("**/*", route -> {
// Runs first.
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.
page.route("**/*", route -> {
if (!route.request().method().equals("GET")) {
route.fallback();
return;
}
// Handling GET only.
// ...
});

// Handle POST requests.
page.route("**/*", route -> {
if (!route.request().method().equals("POST")) {
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.

page.route("**/*", route -> {
// Override headers
Map<String, String> headers = new HashMap<>(route.request().headers());
headers.put("foo", "foo-value"); // set "foo" header
headers.remove("bar"); // remove "bar" header
route.fallback(new Route.ResumeOptions().setHeaders(headers));
});

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

🌐 Use Route.resume() to immediately send the request to the network, other matching handlers won't be invoked in that case.

参数

  • options Route.FallbackOptions (optional)
    • setHeaders Map<String, String> (optional)#

      如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

    • setMethod String (optional)#

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

    • setPostData String | byte[] (optional)#

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

    • setUrl String (optional)#

      如果设置会更改请求 URL。新的 URL 必须与原始 URL 使用相同的协议。更改 URL 不会影响路由匹配,所有路由都是使用原始请求 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.

用法

page.route("https://dog.ceo/api/breeds/list/all", route -> {
APIResponse response = route.fetch();
JsonObject json = new Gson().fromJson(response.text(), JsonObject.class);
JsonObject message = itemObj.get("json").getAsJsonObject();
message.set("big_red_dog", new JsonArray());
route.fulfill(new Route.FulfillOptions()
.setResponse(response)
.setBody(json.toString()));
});

参数

  • options Route.FetchOptions (optional)
    • setHeaders Map<String, String> (optional)#

      如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

    • setMaxRedirects int (optional) Added in: v1.31#

      自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为 20。传入 0 可不跟随重定向。

    • setMaxRetries int (optional) Added in: v1.46#

      网络错误应重试的最大次数。目前仅重试 ECONNRESET 错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为 0 - 不重试。

    • setMethod String (optional)#

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

    • setPostData String | byte[] (optional)#

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

    • setTimeout double (optional) Added in: v1.33#

      请求超时时间(毫秒)。默认值为 30000(30 秒)。传入 0 可禁用超时。

    • setUrl String (optional)#

      如果设置更改请求 URL,则新 URL 必须与原始 URL 使用相同的协议。

返回

详情

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

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


fulfill

Added before v1.9 route.fulfill

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

🌐 Fulfills route's request with given response.

用法

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

🌐 An example of fulfilling all requests with 404 responses:

page.route("**/*", route -> {
route.fulfill(new Route.FulfillOptions()
.setStatus(404)
.setContentType("text/plain")
.setBody("Not Found!"));
});

提供静态文件的示例:

🌐 An example of serving static file:

page.route("**/xhr_endpoint", route -> route.fulfill(
new Route.FulfillOptions().setPath(Paths.get("mock_data.json"))));

参数

  • options Route.FulfillOptions (optional)
    • setBody String (optional)#

      可选的响应主体(文本形式)。

    • setBodyBytes byte[] (optional) Added in: v1.9#

      可选的响应主体(原始字节形式)。

    • setContentType String (optional)#

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

    • setHeaders Map<String, String> (optional)#

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

    • setPath Path (optional)#

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

    • setResponse APIResponse (optional) Added in: v1.15#

      APIResponse 用于满足路由的请求。可以使用 fulfill 选项覆盖响应的各个字段(例如 headers)。

    • setStatus int (optional)#

      响应状态码,默认为 200

返回


request

Added before v1.9 route.request

要路由的请求。

🌐 A request to be routed.

用法

Route.request();

返回


resume

Added before v1.9 route.resume

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

🌐 Sends route's request to the network with optional overrides.

用法

page.route("**/*", route -> {
// Override headers
Map<String, String> headers = new HashMap<>(route.request().headers());
headers.put("foo", "foo-value"); // set "foo" header
headers.remove("bar"); // remove "bar" header
route.resume(new Route.ResumeOptions().setHeaders(headers));
});

参数

  • options Route.ResumeOptions (optional)
    • setHeaders Map<String, String> (optional)#

      如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

    • setMethod String (optional)#

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

    • setPostData String | byte[] (optional)#

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

    • setUrl String (optional)#

      如果设置更改请求 URL,则新 URL 必须与原始 URL 使用相同的协议。

返回

详情

setHeaders 选项适用于路由请求及其发起的任何重定向请求。然而,setUrlsetMethodsetPostData 仅适用于原始请求,并不会应用到重定向请求。

🌐 The setHeaders option applies to both the routed request and any redirects it initiates. However, setUrl, setMethod, and setPostData only apply to the original request and are not carried over to redirected requests.

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

warning

某些请求头是禁止的,无法被覆盖(例如,CookieHostContent-Length 等,完整列表请参见 此 MDN 页面)。如果对禁止的请求头提供了覆盖,它将被忽略,并使用原始的请求头。

🌐 Some request headers are forbidden and cannot be overridden (for example, Cookie, Host, Content-Length and others, see this MDN page for full list). If an override is provided for a forbidden header, it will be ignored and the original request header will be used.

要设置自定义 Cookie,请使用 BrowserContext.addCookies()

🌐 To set custom cookies, use BrowserContext.addCookies().