Node.js 18环境下Undici Fetch请求配置带认证独立代理的解决方案
嘿,刚好在Node.js 18里用Undici Fetch配置代理我熟,这就给你一步步讲清楚,包括带用户名密码认证的情况,完全匹配你要的功能~
使用Undici Fetch配置独立代理(含认证)
基础无认证代理示例
先看最基础的配置,给单个Fetch请求指定独立代理,和你原来的无代理代码功能完全一致,只是多了代理配置:
const { fetch, ProxyAgent } = require("undici"); // 创建对应代理的Agent实例 const proxyAgent = new ProxyAgent("http://your-proxy-address:port"); async function getIPViaProxy() { // 给fetch请求传入dispatcher参数,指定使用这个代理 const response = await fetch('https://ifconfig.me/all', { dispatcher: proxyAgent }); const result = await response.text(); console.log(result); } getIPViaProxy();
带用户名密码认证的代理配置
如果你的代理需要身份验证,有两种实用的配置方式:
方式1:通过代理URL嵌入认证信息
适合快速测试的简单写法(注意:不推荐在生产环境硬编码敏感信息):
const { fetch, ProxyAgent } = require("undici"); // 格式:http://用户名:密码@代理地址:端口 const proxyAgent = new ProxyAgent("http://your-username:your-password@your-proxy-address:port"); async function getIPWithAuthProxy() { const response = await fetch('https://ifconfig.me/all', { dispatcher: proxyAgent }); const result = await response.text(); console.log(result); } getIPWithAuthProxy();
方式2:通过Agent配置项传入认证信息(推荐)
这种方式更安全,你可以从环境变量、配置文件等地方读取敏感信息,避免明文暴露:
const { fetch, ProxyAgent } = require("undici"); // 示例:从环境变量读取敏感信息 const PROXY_USER = process.env.PROXY_USER; const PROXY_PASS = process.env.PROXY_PASS; const PROXY_HOST = process.env.PROXY_HOST; const PROXY_PORT = process.env.PROXY_PORT; const proxyAgent = new ProxyAgent({ uri: `http://${PROXY_HOST}:${PROXY_PORT}`, auth: { username: PROXY_USER, password: PROXY_PASS } }); async function getIPWithSecureAuthProxy() { const response = await fetch('https://ifconfig.me/all', { dispatcher: proxyAgent }); const result = await response.text(); console.log(result); } getIPWithSecureAuthProxy();
关键说明
- 独立代理配置:每个
ProxyAgent实例对应一个代理地址,如果你需要不同请求用不同代理,只需要创建多个ProxyAgent,分别传给对应fetch请求的dispatcher参数即可。 - 为什么用
dispatcher:Undici的Fetch API通过dispatcher选项控制底层请求的分发逻辑,代理配置就是通过这个选项注入的,这是Undici特有的配置方式(和浏览器原生Fetch不同)。 - 代理协议注意:如果你的代理是HTTPS协议,记得把代理URL的协议改成
https://,不过大多数HTTP代理也能处理HTTPS请求(通过CONNECT方法建立隧道)。
内容的提问来源于stack exchange,提问作者Slick




