跳转到内容
搜索文档

Workers 绑定 API

最后更新 查看 MarkdownAgent 设置

VPC 绑定提供了从您的 Worker 访问私有服务的 API。无论是 VPC 服务还是 VPC 网络,都暴露了用于 HTTP 流量的 fetch() 方法。VPC 网络还暴露了用于原始 TCP 连接的 connect() 方法。绑定类型之间的区别在于路由范围,而不是在 API 表面上。

绑定类型

VPC 服务

VPC 服务绑定将请求路由到特定的预注册主机和端口。VPC 服务配置始终决定连接目标,即使在 fetch() 调用中存在不同的 URL 或主机。

  • fetch() 中提供的主机(host)不控制路由。它仅填充 Host 标头,并且在使用 https 时,填充服务器名称指示(SNI)值。
  • fetch() 中提供的端口(port)将被忽略 — 始终使用在 VPC 服务配置中指定的端口。

VPC 网络

VPC 网络绑定授予访问通过绑定的 Cloudflare Tunnel 或通过 Cloudflare Mesh 可访问的任何服务的权限,包括通过 Cloudflare Tunnel 或 Mesh 宣布的子网和主机名路由,以及通过 Cloudflare WAN 接入(GRE、IPsec 或 CNI)连接的目标。传递给 fetch() 的 URL 或传递给 connect() 的地址决定了实际目标,即主机名或 IP 地址和端口。

fetch()

通过绑定的 Cloudflare Tunnel 或 Cloudflare Mesh 向私有服务发出 HTTP 请求。在 VPC 服务和 VPC 网络绑定上均可用。

const response = await env.MY_BINDING.fetch(resource, options);

参数

  • resource (string | URL | Request) — 要获取的 URL。必须是包含协议、主机和路径的绝对 URL(例如,http://internal-api/api/users)。
  • options (可选 RequestInit) — 标准的 fetch 选项,包括:
    • method — HTTP 方法(GET、POST、PUT、DELETE 等)
    • headers — 请求标头
    • body — 请求主体
    • signal — 用于取消请求的 AbortSignal

返回值

返回一个解析为标准 Fetch API Response 对象Promise<Response>

示例

以下示例适用于 VPC 服务和 VPC 网络绑定。

基本的 GET 请求

export default {
	async fetch(request, env) {
		const privateRequest = new Request(
			"http://internal-api.company.local/users",
		);
		const response = await env.MY_BINDING.fetch(privateRequest);
		const users = await response.json();

		return new Response(JSON.stringify(users), {
			headers: { "Content-Type": "application/json" },
		});
	},
};

带主体的 POST 请求

export default {
	async fetch(request, env) {
		const privateRequest = new Request(
			"http://internal-api.company.local/users",
			{
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bearer ${env.API_TOKEN}`,
				},
				body: JSON.stringify({
					name: "John Doe",
					email: "[email protected]",
				}),
			},
		);

		const response = await env.MY_BINDING.fetch(privateRequest);

		if (!response.ok) {
			return new Response("Failed to create user", { status: response.status });
		}

		const user = await response.json();
		return new Response(JSON.stringify(user), {
			headers: { "Content-Type": "application/json" },
		});
	},
};

具有 HTTPS 和 IP 地址的请求

export default {
	async fetch(request, env) {
		const privateRequest = new Request("https://10.0.1.50/api/data");
		const response = await env.MY_BINDING.fetch(privateRequest);

		return response;
	},
};

connect()

通过绑定的 Cloudflare Tunnel 或 Cloudflare Mesh 打开到私有目标的原始 TCP 连接。仅在 VPC 网络绑定上可用。

const socket = await env.MY_BINDING.connect(address);

参数

  • address (string | SocketAddress) — 要连接的目标。传递格式为 "host:port" 的字符串(例如,"10.0.1.50:6379")或包含 hostnameportSocketAddress 对象。

返回值

返回一个解析为具有 readablewritable 流的 SocketPromise<Socket>。如果 connect() 无法建立连接,它将抛出异常。

示例

连接到私有 Redis 实例

export default {
	async fetch(request, env) {
		const socket = await env.MY_BINDING.connect("10.0.1.50:6379");

		const writer = socket.writable.getWriter();
		await writer.write(new TextEncoder().encode("PING\r\n"));
		await writer.close();

		return new Response(socket.readable);
	},
};

使用 SocketAddress 对象进行连接

export default {
	async fetch(request, env) {
		const socket = await env.MY_BINDING.connect({
			hostname: "10.0.1.50",
			port: 6379,
		});

		const writer = socket.writable.getWriter();
		await writer.write(new TextEncoder().encode("PING\r\n"));
		await writer.close();

		return new Response(socket.readable);
	},
};

所需角色

要在 Worker 中绑定 VPC 服务或 VPC 网络,您的用户需要具备 Connectivity Directory Bind(或 Connectivity Directory Admin)角色。通过 VPC 网络绑定直接绑定到 Cloudflare Tunnel 需要 Connectivity Directory Admin。有关角色定义,请参阅角色

后续步骤

这篇文档对您有帮助吗?