在NodeJS中为任何请求使用自定义DNS解析器

g6ll5ycj  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(132)

我正在寻找一种方法来使用node-fetch为nodejs请求使用自定义DNS解析器。我认为这里有一个解释的星星:Node override request IP resolution,但我无法管理它对任何请求都有效。我的目标是使用替代DNS解析器,如cloudflare(1.1.1.1)或Google公共DNS(8.8.8.8),而不是OS / ISP默认的DNS解析。

import http from "http";
import https from "https";
import fetch from "node-fetch";

const staticLookup = (ip: string, v?: number) => (hostname: string, _: null, cb: Function) => {
  cb(null, ip, v || 4);
};

const staticDnsAgent = (scheme: "http" | "https", ip: string) => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup(ip), rejectUnauthorized: false });
};

// Both request are not working
fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https", "1.1.1.1")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http", "8.8.8.8")
})

字符串
我正在努力寻找一种方法来使这个例子工作,我很确定我必须使用nodejs DNS模块并设置一个自定义服务器。

stszievb

stszievb1#

感谢Martheen在我的第一篇文章中回答,我能够在这里实现结果:

import http from "http";
import https from "https";
import dns from "dns/promises";
import fetch from "node-fetch";

// Cloud flare dns
dns.setServers([
  "1.1.1.1",
  "[2606:4700:4700::1111]",
]);

const staticLookup = () => async (hostname: string, _: null, cb: Function) => {
  const ips = await dns.resolve(hostname);

  if (ips.length === 0) {
    throw new Error(`Unable to resolve ${hostname}`);
  }

  cb(null, ips[0], 4);
};

const staticDnsAgent = (scheme: "http" | "https") => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup() });
};

fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http")
})

字符串

ni65a41a

ni65a41a2#

要在Node.js脚本中为所有fetch()请求使用自定义DNS服务器,您可以使用undici库配置全局请求代理。

**第一步:**安装undici如下:

npm install undici

字符串

**第二步:**使用您的DNS服务器配置设置全局代理:

import { Agent, setGlobalDispatcher } from "undici";

// Replace with your custom DNS server IP
const DnsIp = "127.0.0.1";

const agent = new Agent({
  connect: {
    // The third argument refers to the IP family (4 for IPv4, 6 for IPv6)
    lookup: (_hostname, _options, callback) => callback(null, DnsIp, 4)
  },
});

// Set the custom agent as the global dispatcher
setGlobalDispatcher(agent);

// Example: Use the DNS server at 127.0.0.1 to resolve git.dev
const response = await fetch("https://git.dev/");


这已经用Node.js v18测试过了。注意,node-fetch包不是必需的。

相关问题