# Node.js 代理接入示例

使用 undici ProxyAgent、环境变量、AbortSignal 超时和安全日志完成代理请求。

Node.js 示例使用调用方项目锁定的 `undici` 依赖。`PROXY_URL` 格式为 `http://<proxy-username>:<proxy-password>@<gateway-host>:<gateway-port>`。

## Node.js

```javascript
import { ProxyAgent, fetch } from 'undici';

const dispatcher = new ProxyAgent(process.env.PROXY_URL);
try {
  const response = await fetch('https://<public-test-host>/ip', {
    dispatcher,
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  console.log(await response.json());
} finally {
  await dispatcher.close();
}
```

## 配置

- 从受控环境变量读取代理 URL。
- 不要把代理 URL 输出到控制台。

## 请求

- 将 `ProxyAgent` 作为 fetch dispatcher。
- 使用 `AbortSignal.timeout` 设置整体截止时间。

## 资源释放

- 示例结束后关闭 agent。
- 生产连接池按代理身份复用并在配置变更时淘汰。

## 错误处理

- 区分超时、代理认证和目标状态。
- 日志只记录任务 ID 与状态。

html pre.shiki code .szBVR, html code.shiki .szBVR{--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sVt8B, html code.shiki .sVt8B{--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}
