对于 Express 一侧使用环境代理策略的 HTTPS 调用:

import https from 'node:https';
import { ProxyAgent } from 'proxy-agent';

const agent = new ProxyAgent();
const request = https.get('https://service.example/data', { agent }, response => {
  console.log(response.statusCode);
  response.resume();
});
request.on('error', error => console.error(error.message));

当前的 ProxyAgent 构造函数接收一个选项对象。不做覆盖时,它通过 proxy-from-env 读取受支持的环境策略,并为该 URL 选择较低层的 agent。

对于应用自己持有的固定路由,通过该选项对象替换选择:

new ProxyAgent({ getProxyForUrl: () => proxyUrl })

常量 callback 不会套用默认环境的 NO_PROXY 决定。替换它时,请在选择器中实现必需的直连例外。

对于获准的公共服务调用,免费代理列表 提供 proxyUrl 的候选;请选择 agent 支持的协议。返回的代理 URL 的 scheme 标明中间层协议;https.get 仍然指向真实服务。按工作负载保留该 agent,并在关闭时销毁。

Express 监听器只接收传入请求,不配置这条出站连接。基于 Undici 的 fetch 也使用另一种传输输入:Undici 配合 ProxyAgent 的 fetch 接收一个 dispatcher,并使用与 Node 运行时兼容的包版本。

相关文章