在Node JS中使用Undici Fetch请求代理



问题

我不确定如何使用Undici fetch的代理。如果适用的话,我希望对任何带有用户名和密码身份验证的提取请求使用单独的代理。我已经找到了一些关于代理的文档,但我还没有看到太多关于将代理与fetchapi一起使用的内容。

解决方案

至于一个好的解决方案,我希望有一个代码示例,使用代理执行对网站(例如ifconfig.me)的简单get请求,并说明如何在该代理中包含用户名和密码。

该解决方案应该执行与以下代码相同的功能,但使用代理:

const { fetch } = require("undici");
const req = await fetch('https://ifconfig.me/all');
const res = await req.text();
正在使用节点版本18

在此处找到解决方案https://github.com/nodejs/undici/blob/e461407c63e1009215e13bbd392fe7919747ab3e/docs/api/ProxyAgent.md

在我的情况下,我使用

const client = new ProxyAgent(`http://${proxy.user}:${proxy.pass}@${proxy.host}:${proxy.port}`);
const response = await fetch(urlRequested, {  dispatcher: client  });

最新更新