让 node-fetch 在重定向后自行选择代理 agent
为 HTTP 与 HTTPS 目标传入 agent 函数,这样重定向后仍能选中匹配的代理 agent。
首个 URL 可能是 HTTPS,而重定向后的 URL 是 HTTP。应按每个请求的目标选择 agent,而不是把一个 agent 绑定在首个 URL 上。
对于 ESM 应用中导入的 node-fetch 包,传入一个函数:
import fetch from 'node-fetch';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyUrl = 'http://proxy.example:8080';
const httpAgent = new HttpProxyAgent(proxyUrl);
const httpsAgent = new HttpsProxyAgent(proxyUrl);
const response = await fetch('https://api.example/', {
agent: url => url.protocol === 'http:' ? httpAgent : httpsAgent,
});替换 API 地址和代理端点。对于允许通过公共中介访问的公共 API,HTTP 代理列表可为 proxyUrl 提供候选。两个 agent 可以共用同一个 HTTP 代理监听端口;它们的名字指的是对目标发起的请求。
| 传给选择器的 URL | 选中的 agent |
|---|---|
| https://… | httpsAgent |
| http://… | httpAgent |
因此,即使重定向改变了目标协议,该函数仍会选中匹配的 agent。proxyUrl 独立于这一判断,始终描述中间代理。
agent 应按工作负载创建一次并复用。处理返回的状态,并在调用方代码中读取响应正文。这个 agent 接口属于 node-fetch;Node 内置的 fetch 使用另一套传输接口。