如何结合http_proxy、no_proxy环境变量使用ProxyAgent
使用ProxyAgent处理http_proxy/https_proxy及no_proxy的问题
1. 实例化ProxyAgent时的URI传入方式
你之前的写法不准确,ProxyAgent v6.4.0的构造函数支持两种传入方式:
- 直接传入代理URI字符串:
new ProxyAgent(process.env.http_proxy) - 或者通过
ProxyAgentOptions的proxy字段传入(并非uri):new ProxyAgent({ proxy: process.env.http_proxy })
ProxyAgentOptions核心结构包含代理地址相关的proxy字段,同时继承了Node.js原生Agent的通用配置(比如keepAlive、maxSockets等)。
2. http_proxy和https_proxy的判断逻辑
ProxyAgent不会自动根据请求协议选择对应环境变量,这个逻辑需要你自行实现。示例如下:
function getProxyForRequest(url) { const { protocol } = new URL(url); return protocol === 'https:' ? process.env.https_proxy || process.env.http_proxy : process.env.http_proxy; } // 使用示例 const targetUrl = 'https://example.com'; const proxy = getProxyForRequest(targetUrl); const agent = proxy ? new ProxyAgent(proxy) : undefined;
3. no_proxy列表的处理
ProxyAgent同样不内置支持no_proxy规则解析,需要自行编写逻辑判断目标主机是否在豁免列表中,示例如下:
function shouldUseProxy(targetUrl) { const noProxyList = (process.env.no_proxy || '') .split(',') .map(item => item.trim()) .filter(Boolean); if (noProxyList.length === 0) return true; const { hostname } = new URL(targetUrl); // 支持精确域名和后缀匹配(如.example.com) return !noProxyList.some(rule => { if (rule.startsWith('.')) { return hostname.endsWith(rule) || hostname === rule.slice(1); } return hostname === rule; }); } // 使用示例 const targetUrl = 'https://example.com'; if (shouldUseProxy(targetUrl)) { const proxy = getProxyForRequest(targetUrl); const agent = new ProxyAgent(proxy); // 发起请求时传入agent } else { // 不使用代理直接请求 }
内容的提问来源于stack exchange,提问作者theguy
相关产品推荐
相关产品推荐

