对 NodeJS 中的任何请求使用自定义 DNS 解析器

Use Custom DNS resolver for any request in NodeJS

我正在寻找一种方法来使用自定义 DNS 解析器来处理使用 node-fetch 的 nodejs 请求。我认为这里有一个解释的明星: 但我无法让它适用于任何请求。我的目标是使用替代 DNS 解析器,例如 cloudflare (1.1.1.1) 或 Google public 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 模块并设置自定义服务器。

感谢 Martheen 在我的第一个 post 中回答,我能够在这里取得结果:

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")
})