---
title: "Node.js 代理设置：fetch、undici 与 SOCKS5 | Proxonym"
description: "在 Node.js 中通过 fetch 和 undici ProxyAgent 使用代理：身份验证、轮换与粘性 IP、地理定位、SOCKS5 以及重试处理。"
url: https://proxonym.com/zh/integrations/nodejs
updated: 2026-10-02T03:03:46+00:00
---

# 如何在 Node.js 中使用代理

Node.js 可借助 undici 的 ProxyAgent，通过代理发送 fetch 请求。本指南演示如何在 Proxonym 网关完成认证、轮换或固定 IP、定位指定地区、添加 SOCKS5 支持以及出错重试。

- 共 6 步
- 12 分钟完成配置
- 复制即用的代码

开始之前

- Node.js 22 或更高版本
- undici 8 或更高版本；如需 SOCKS5，还需安装 socks-proxy-agent
- Proxonym 住宅代理或移动代理套餐

连接参数

- **主机**: `gw.proxonym.com`
- **HTTP**: `8000`
- **SOCKS5**: `1080`
- **用户名**: `USERNAME-country-us`

1. **安装依赖包**: 安装 undici 用于 HTTP 代理；如果计划使用 SOCKS5，还需安装 socks-proxy-agent。将示例保存为 `.mjs` 文件，这样无需额外配置即可使用 `import` 和顶层 `await`。 Shell `npm install undici socks-proxy-agent`
2. **通过网关发送请求**: 使用网关地址和 Basic 类型的 Proxy-Authorization 令牌创建 ProxyAgent，然后将其作为 dispatcher 传给 `fetch`。脚本会输出目标网站看到的出口 IP。 JavaScript `// check-ip.mjs import { fetch, ProxyAgent } from 'undici'; const dispatcher = new ProxyAgent({ uri: 'http://gw.proxonym.com:8000', token: 'Basic ${Buffer.from('USERNAME:PASSWORD').toString('base64')}', }); const res = await fetch('https://api.ipify.org', { dispatcher }); console.log('Exit IP:', await res.text()); await dispatcher.close();`
3. **轮换 IP 或保持同一 IP**: ProxyAgent 会复用其连接，而每个连接都固定对应一个出口 IP。如需轮换 IP，请为每个请求新建一个 agent；也可以复用一个带 `-session-` ID 的 agent，将同一 IP 最长保持 120 分钟。 JavaScript `// sessions.mjs import { randomBytes } from 'node:crypto'; import { fetch, ProxyAgent } from 'undici'; function proxonymAgent({ country, state, city, asn, session, lifetime = 30 } = {}) { let user = 'USERNAME'; if (country) user += '-country-${country}'; if (state) user += '-state-${state}'; if (city) user += '-city-${city}'; if (asn) user += '-asn-${asn}'; if (session) user += '-session-${session}-lifetime-${lifetime}'; return new ProxyAgent({ uri: 'http://gw.proxonym.com:8000', token: 'Basic ${Buffer.from('${user}:PASSWORD').toString('base64')}', }); } // Rotating: a new agent opens a new connection, so each request gets a new IP for (let i = 0; i < 3; i++) { const agent = proxonymAgent({ country: 'us' }); const res = await fetch('https://api.ipify.org', { dispatcher: agent }); console.log('rotating', await res.text()); await agent.close(); } // Sticky: one agent and one session ID keep the same IP for up to 30 minutes const sticky = proxonymAgent({ country: 'us', session: randomBytes(4).toString('hex') }); for (let i = 0; i < 3; i++) { const res = await fetch('https://api.ipify.org', { dispatcher: sticky }); console.log('sticky', await res.text()); } await sticky.close();`
4. **定位国家、州、城市或 ASN**: 将位置选项传给上一步中的 `proxonymAgent()` 辅助函数。使用小写的 ISO 国家代码，空格用下划线代替，例如 `{ country: 'us', state: 'new_york' }` 或 `{ country: 'us', asn: 7922 }`。 JavaScript `const agent = proxonymAgent({ country: 'de', city: 'berlin' }); const res = await fetch('https://ipinfo.io/json', { dispatcher: agent }); const { ip, city, country } = await res.json(); console.log(ip, city, country); await agent.close();`
5. **使用 SOCKS5 端点**: undici 对 SOCKS5 的支持仍标记为实验性功能，因此本示例将 socks-proxy-agent 与 `https` 模块搭配使用；同一个 agent 也适用于 axios 以及其他接受 agent 的客户端。`socks5h://` 协议前缀会让代理负责解析主机名。 JavaScript `// socks5.mjs import https from 'node:https'; import { SocksProxyAgent } from 'socks-proxy-agent'; const agent = new SocksProxyAgent('socks5h://USERNAME-country-gb:PASSWORD@gw.proxonym.com:1080'); https.get('https://api.ipify.org', { agent }, (res) => { let body = ''; res.on('data', (chunk) => (body += chunk)); res.on('end', () => console.log('Exit IP:', body)); });`
6. **重试网关错误**: 当网关拒绝建立隧道时，`fetch` 会抛出错误，最内层的 `err.cause` 会指明网关状态码。遇到 429、502 和 504 时，短暂退避后重试；遇到 407、402 或 403 时则应停止，它们分别指向凭据、余额或目标网站被屏蔽的问题。 JavaScript `// retry.mjs import { fetch, ProxyAgent } from 'undici'; const dispatcher = new ProxyAgent({ uri: 'http://gw.proxonym.com:8000', token: 'Basic ${Buffer.from('USERNAME-country-us:PASSWORD').toString('base64')}', }); // The innermost cause carries the gateway status, e.g. "Proxy response (407) !== 200 when HTTP Tunneling" function rootCause(err) { let cause = err; while (cause?.cause) cause = cause.cause; return cause; } async function fetchWithRetry(url, tries = 3) { for (let attempt = 1; ; attempt++) { try { const res = await fetch(url, { dispatcher, signal: AbortSignal.timeout(60_000) }); if ((res.status !== 429 && res.status < 500) || attempt === tries) return res; await res.body?.cancel(); } catch (err) { const reason = rootCause(err).message; console.error('attempt ${attempt}:', reason); // 402, 403 and 407 will not go away on a retry if (/\((402|403|407)\)/.test(reason) || attempt === tries) throw err; } await new Promise((resolve) => setTimeout(resolve, 1000 * attempt)); } } const res = await fetchWithRetry('https://example.com'); console.log('Status:', res.status); await dispatcher.close();`

## 常见问题

### Node.js 内置的 fetch 能使用代理吗？

可以，有两种方式。在 Node.js 24 等较新版本中，设置 NODE_USE_ENV_PROXY=1 后，全局 fetch 会经由 HTTPS_PROXY 中的代理发送请求，适合使用单个固定代理 URL 的场景。如果需要按请求控制会话和位置，请安装 undici，并从中同时导入 fetch 和 ProxyAgent，以确保客户端与 dispatcher 始终使用同一版本。

### 如何在 axios 中使用 Proxonym？

安装 https-proxy-agent，创建 new HttpsProxyAgent("http://USERNAME:PASSWORD@gw.proxonym.com:8000")，将其作为 httpsAgent 传入，同时把 proxy 设为 false。如需 SOCKS5，以同样的方式传入 SocksProxyAgent 即可。每个 agent 都有自己的连接池，因此要并行运行多个粘性会话时，请为每个会话分别创建 agent。

### 为什么没有会话参数，请求仍保持同一个 IP？

网关按连接分配 IP，而 undici 会保持长连接，因此通过同一个 agent 发往同一主机的连续请求会走同一条隧道。如果每次调用都必须从不同的 IP 发出，请在两次请求之间关闭 agent、为每个请求新建 agent，或为每个请求添加随机会话 ID。

### “Proxy response (407) !== 200 when HTTP Tunneling”是什么意思？

这是网关拒绝 CONNECT 请求时 undici 附加的错误信息，位于最内层的 err.cause 中，括号里的数字就是网关状态码。407 表示凭据错误，402 表示余额已用完或套餐已过期，403 表示目标网站受可接受使用政策限制而被屏蔽。502 和 504 是暂时性错误，配合退避策略重试即可。

技巧与注意事项

- 请从同一个 undici 包中导入 fetch 和 ProxyAgent，因为把从 npm 安装的 ProxyAgent 交给 Node.js 内置的 fetch 使用时，如果两者版本不同，可能会出错。
- 共用一个 agent 的请求会复用其连接，也就会沿用同一个出口 IP，因此轮换 IP 需要新建 agent 或新建连接。
- 使用 axios 时，将 https-proxy-agent 包中的 HttpsProxyAgent 作为 httpsAgent 传入，并把 proxy 设为 false，以免 axios 套用自身的代理处理逻辑。
- 从 process.env 读取凭据，不要硬编码在代码中，尤其是存放在共享代码仓库中的代码。

延伸阅读

- [如何抓取 Google 搜索结果：自建代理与 SERP API 对比](https://proxonym.com/zh/blog/scrape-google-search-results)
- [轮换代理与粘性代理：如何选择合适的会话类型](https://proxonym.com/zh/blog/rotating-vs-sticky-sessions)

卡在某一步了？

大多数故障都可以从错误代码中找到原因。请先查看错误代码，再单独测试代理。

- [帮助中心](https://proxonym.com/zh/help)
- [网关错误代码](https://proxonym.com/zh/docs#errors-and-troubleshooting)
- [测试您的代理](https://proxonym.com/zh/proxy-checker)

## 更多集成指南

[全部集成](https://proxonym.com/zh/integrations)

- [Playwright (JavaScript 库)](https://proxonym.com/zh/integrations/playwright)
- [Puppeteer (JavaScript 库)](https://proxonym.com/zh/integrations/puppeteer)
- [AdsPower (指纹浏览器)](https://proxonym.com/zh/integrations/adspower)
