使用 undici 为 Node.js 原生 fetch 请求设置代理

在 Node.js 项目中,有时需要通过代理服务器发送 HTTP 请求。然而,许多第三方库(如原生 fetch)无法直接支持 https-proxy-agentsocks-proxy-agent 等代理库。在这种情况下,可以通过 undici 提供的全局调度器为请求设置代理。

一、为什么使用 undici 处理代理

在 Node.js 中,原生 fetch 和部分第三方库无法直接使用 https-proxy-agentsocks-proxy-agent 进行代理。为了解决这一问题,可以借助 undici 库,通过其全局调度器(Global Dispatcher)功能实现代理设置。undici 是一个高效的 HTTP 客户端,提供了对代理服务器的全面支持。

二、通过 undici 设置全局代理

要在 Node.js 中为所有请求统一设置代理,可以利用 undici 的全局调度器。以下是一个简单的例子,演示如何使用 HTTP 和 SOCKS5 代理发送请求。

1. 安装 undici 依赖

在项目中使用 undici,首先需要安装该库:

bash 复制代码
npm install undici

2. 使用 HTTP 代理进行请求

以下代码展示了如何通过 undici 设置 HTTP 代理,并使用原生 fetch 进行请求。

js 复制代码
const { setGlobalDispatcher, ProxyAgent } = require("undici");

// 设置 HTTP 代理
const httpDispatcher = new ProxyAgent({ uri: "<http://127.0.0.1:7899>" });
setGlobalDispatcher(httpDispatcher);

// 请求获取 IP 地址
const getIP = async () => {
  fetch("<https://httpbin.org/ip>", {
    headers: {
      "User-Agent": "Mozilla/5.0 (compatible; curl/7.64.1)",
      Accept: "*/*",
    },
  })
    .then((res) => res.json())
    .then((res) => {
      console.log("通过 HTTP 代理获取到的 IP:", res);
    })
    .catch((err) => console.log("请求失败:", err));
};

getIP();

该示例中,通过 HTTP 代理访问 https://httpbin.org/ip 接口,并返回客户端的 IP 地址。

3. 使用 SOCKS5 代理进行请求

如果需要使用 SOCKS5 代理,只需将 uri 设置为 SOCKS5 代理地址:

js 复制代码
const socks5Dispatcher = new ProxyAgent({ uri: "socks5://127.0.0.1:1080" });
setGlobalDispatcher(socks5Dispatcher);

通过该方式,所有请求将通过 SOCKS5 代理进行。

三、未使用代理的请求示例

为了对比代理前后的效果,以下代码展示了未使用代理时的请求:

js 复制代码
const getIPWithoutProxy = async () => {
  fetch("<https://httpbin.org/ip>", {
    headers: {
      "User-Agent": "Mozilla/5.0 (compatible; curl/7.64.1)",
      Accept: "*/*",
    },
  })
    .then((res) => res.json())
    .then((res) => {
      console.log("未使用代理获取到的 IP:", res);
    })
    .catch((err) => console.log("请求失败:", err));
};

getIPWithoutProxy();

此请求不会经过代理服务器,获取到的 IP 地址为客户端本机的外网 IP。

总结

通过 undici 库的全局调度器功能,可以轻松为 Node.js 中的原生 fetch 请求配置代理。无论是 HTTP 还是 SOCKS5 代理,均可通过 ProxyAgent 设置,并通过 setGlobalDispatcher 方法统一应用到所有请求。这种方法适合需要在项目中全局配置代理的场景,避免了为每个请求单独设置代理的麻烦,同时提高了代码的可维护性。

相关推荐
Doris8934 小时前
【JS】Web APIs BOM与正则表达式详解
前端·javascript·正则表达式
建南教你种道德之花4 小时前
浏览器缓存完全指南:从原理到实践
前端
linzeyang4 小时前
Advent of Code 2025 挑战全手写代码 Day 5 - 餐厅
后端·python
yeshihouhou4 小时前
springboot集成redis -RedisTemplate使用
spring boot·redis·后端
1024小神4 小时前
swiftui中view分为几种类型?各有什么特点
前端
Java水解4 小时前
Spring Boot 中的 @ConditionalOnBean 注解详解
spring boot·后端
局i4 小时前
v-for 与 v-if 的羁绊:Vue 中列表渲染与条件判断的爱恨情仇
前端·javascript·vue.js
suke4 小时前
紧急高危:Next.js 曝出 CVSS 10.0 级 RCE 漏洞,请立即修复!
前端·程序员·next.js