> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 fetch() 代理 HTTP 请求

在 Bun 中，`fetch` 支持通过 HTTP 或 HTTPS 代理发送请求。这在公司网络中或需要确保请求通过特定 IP 地址发送时非常有用。

```ts proxy.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
await fetch("https://example.com", {
  // 代理服务器的 URL
  proxy: "https://username:password@proxy.example.com:8080",
});
```

***

`proxy` 选项可以是 URL 字符串，也可以是包含 `url` 和可选 `headers` 的对象。如果代理需要身份验证，URL 中可以包含用户名和密码。代理地址可以是 `http://` 或 `https://`。

***

## 自定义代理请求头

如果需要向代理服务器发送自定义头（用于代理认证令牌、自定义路由等），可以使用对象格式：

```ts proxy-headers.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
await fetch("https://example.com", {
  proxy: {
    url: "https://proxy.example.com:8080",
    headers: {
      "Proxy-Authorization": "Bearer my-token",
      "X-Proxy-Region": "us-east-1",
    },
  },
});
```

`headers` 属性可以是普通对象或 `Headers` 实例。这些请求头会直接发送给代理服务器，用于 `CONNECT` 请求（针对 HTTPS 目标）或代理请求（针对 HTTP 目标）。

如果你提供了 `Proxy-Authorization` 请求头，它会覆盖代理 URL 中指定的任何凭据。

***

## 环境变量

你也可以通过设置 `$HTTP_PROXY` 或 `$HTTPS_PROXY` 环境变量为代理 URL 来使用代理。这在希望所有请求使用同一代理时很有用。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
HTTPS_PROXY=https://username:password@proxy.example.com:8080 bun run index.ts
```
