跳转到内容
搜索文档

Fetch

最后更新 查看 MarkdownAgent 设置

Fetch API 提供在 Worker 内通过 HTTP 请求异步获取资源的接口。

语法

export default {
	async scheduled(controller, env, ctx) {
		return await fetch("https://example.com", {
			headers: {
				"X-Source": "Cloudflare-Workers",
			},
		});
	},
};
addEventListener("fetch", (event) => {
	// NOTE: can’t use fetch here, as we’re not in an async scope yet
	event.respondWith(eventHandler(event));
});

async function eventHandler(event) {
	// fetch can be awaited here since `event.respondWith()` waits for the Promise it receives to settle
	const resp = await fetch(event.request);
	return resp;
}
from workers import WorkerEntrypoint, Response, fetch

class Default(WorkerEntrypoint):
    async def scheduled(self, controller, env, ctx):
  			return await fetch("https://example.com", headers={"X-Source": "Cloudflare-Workers"})
  • fetch(resource, options optional) : Promise<Response>
  • Fetch 返回一个指向 Response 的 promise。

参数

  • resource Request | string | URL

  • options options

    • cache undefined | 'no-store' | 'no-cache' optional
      • 标准 HTTP cache 标头。仅支持 cache: 'no-store'cache: 'no-cache'。 任何其他 cache 标头都会导致 TypeError,错误消息为 Unsupported cache mode: <attempted-cache-mode>。 _ 对于所有请求,这会将 Pragma: no-cacheCache-Control: no-cache 标头转发到源站。 _ 对于 no-store,发往非 Cloudflare 托管源站的请求会绕过 Cloudflare 缓存。 _ 对于 no-cache,发往非 Cloudflare 托管源站的请求在响应前会强制与源站重新验证。
    • 定义请求内容和行为的对象。

Accept-Encoding 标头的处理方式

使用 fetch() API 发起子请求时,您可以通过包含 Accept-Encoding 标头来指定希望服务器响应时使用的压缩形式(如果服务器支持)。

Workers 支持 gzip 和 brotli 压缩算法。通常,在 Workers 运行时生产环境中无需指定 Accept-EncodingContent-Encoding 标头——从源站获取时会自动请求 brotli 或 gzip 压缩,并在向客户端返回数据时应用压缩,具体取决于客户端和源站服务器的能力。

要从源站请求 brotli,必须在 Worker 中启用 brotli_content_encoding 兼容性标志。很快,此兼容性标志将在即将到来的兼容性日期之后默认对所有 Worker 启用。

透传行为

Accept-Encoding 标头的一个有用场景是将压缩数据从服务器透传给客户端,Accept-Encoding 允许 Worker 直接从服务器接收压缩数据流,而无需事先解压。只要您在返回给客户端之前不读取压缩响应的正文,并保持 Content-Encoding 标头不变,数据就会"透传",无需解压后重新压缩。这在 Worker 位于源站服务器之前,或获取压缩媒体资源时很有帮助,可确保 Worker 返回的响应使用与源站服务器相同的压缩方式。

除了内容编码变化外,当响应使用的编码不受客户端支持时,也需要重新压缩。例如,当 Worker 请求 brotli 或 gzip 编码但客户端仅支持 gzip 时,如果服务器向 Worker 返回 brotli 编码数据,仍需要重新压缩(会自动应用)。请注意,此行为也可能因 compression rules 而异,compression rules 可用于在服务器端配置对不同数据类型应用的压缩。

export default {
	async fetch(request) {
		// Accept brotli or gzip compression
		const headers = new Headers({
			"Accept-Encoding": "br, gzip",
		});
		let response = await fetch("https://developers.cloudflare.com", {
			method: "GET",
			headers,
		});

		// As long as the original response body is returned and the Content-Encoding header is
		// preserved, the same encoded data will be returned without needing to be compressed again.
		return new Response(response.body, {
			status: response.status,
			statusText: response.statusText,
			headers: response.headers,
		});
	},
};

相关资源

这篇文档对您有帮助吗?