-
安装依赖包
安装 undici 用于 HTTP 代理;如果计划使用 SOCKS5,还需安装 socks-proxy-agent。将示例保存为
.mjs文件,这样无需额外配置即可使用import和顶层await。Shell npm install undici socks-proxy-agent -
通过网关发送请求
使用网关地址和 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(); -
轮换 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(); -
定位国家、州、城市或 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(); -
使用 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)); }); -
重试网关错误
当网关拒绝建立隧道时,
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 是暂时性错误,配合退避策略重试即可。
