如何在 Node.js 中配置代理(Axios 与原生 Fetch)
更新于:
Axios 内置的 proxy: { host, port } 选项在请求 https:// 目标站点时会发生失败,因为其不会发起建立 HTTP CONNECT 隧道。为了在 Node.js 与 TypeScript 项目中干净稳定地通过 VinaProxy 带认证的 HTTP(S) 代理路由流量,请在 Axios 中使用 HttpsProxyAgent(https-proxy-agent),或在原生 Node fetch() 中使用 undici.ProxyAgent 调度器。
new HttpsProxyAgent('http://user:pass@ip:port')- 1 个IP₫40,000
- 5+ 个IP₫35,000
- 10+ 个IP₫25,000
- 20+ 个IP₫25,000
- 50+ 个IP₫25,000
- 100+ 个IP₫25,000
- 200+ 个IP₫25,000
- 500+ 个IP₫25,000
- 1000+ 个IP₫22,000
- 2000+ 个IP₫20,000
- 1 个IP₫40,000
- 5+ 个IP₫35,000
- 10+ 个IP₫25,000
- 20+ 个IP₫25,000
- 50+ 个IP₫25,000
- 100+ 个IP₫25,000
- 200+ 个IP₫25,000
- 500+ 个IP₫25,000
- 1000+ 个IP₫22,000
- 2000+ 个IP₫20,000
Axios 与原生 Node.js fetch() 代理配置对比
两种类库均支持直接使用来自 VinaProxy 控制台的标准 http://user:pass@ip:port URL 格式:
| HTTP 客户端 | 依赖 NPM 包 | 推荐代码示例 |
|---|---|---|
| Axios | npm i https-proxy-agent | axios.get(url, { httpsAgent: new HttpsProxyAgent('http://user:pass@ip:port'), proxy: false }) |
原生 fetch (Node 18+) | npm i undici | fetch(url, { dispatcher: new ProxyAgent('http://user:pass@ip:port') }) |
| Got | npm i hpagent | got(url, { agent: { https: new HttpsProxyAgent({ proxy: 'http://user:pass@ip:port' }) } }) |
Node.js 中的连接池复用与超时设置最佳实践
- 在 Axios 中配置
httpsAgent时务必同时声明proxy: false,防止 Axios 被操作系统中冲突的HTTP_PROXY环境变量干扰 - 在循环外部为每个代理 IP 仅实例化一次
HttpsProxyAgent或ProxyAgent,以复用底层的持久 TCP keep-alive 连接并减少开销 - 利用我们的 代理格式转换工具 直接将 VinaProxy 代理列表导出为 JSON 数组格式,方便代码直接引入
操作步骤
- 1
安装 https-proxy-agent(或 undici)
在 Node.js 项目根目录下运行
npm install axios https-proxy-agent。 - 2
创建 HttpsProxyAgent 实例
使用你的 VinaProxy 凭证初始化
const agent = new HttpsProxyAgent('http://user:pass@ip:port');。 - 3
将 httpsAgent 与 proxy: false 传入 Axios
调用
const res = await axios.get('https://vinaproxy.com/api/my-ip', { httpsAgent: agent, proxy: false, timeout: 10000 });。 - 4
验证出口 IP 地址
打印
res.data,确认响应确由你分配的专属代理 IP 节点返回。
常见问题
为什么 Axios 默认的 proxy: { host, port, auth } 在请求 HTTPS 时会失败?
Axios 内置的 proxy 配置仅发送明文 HTTP 请求,而不会建立 HTTP CONNECT TLS 加密隧道。配合 proxy: false 使用 httpsAgent: new HttpsProxyAgent('http://user:pass@ip:port') 即可完美解决该问题。
如何在 Node.js 18/20/22 的原生 fetch() 中使用代理?
从 undici 中导入 ProxyAgent,并在 fetch() 的选项对象中传入 { dispatcher: new ProxyAgent('http://user:pass@ip:port') }。
是否可以将代理列表直接转换为适合 Node.js 读取的 JSON 格式?
可以。将 ip:port:user:pass 列表粘贴至我们免费的 代理格式转换工具,并选择导出为 JSON 即可。
使用独享静态 IP 赋能你的 Node.js 后端与爬虫程序
覆盖 7 大国家地区的即时开通、不限流量独享 IPv4 与静态 ISP 代理服务。
购买 Node.js 代理