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

Som*_*one 6 dns node.js

我正在寻找一种方法,使用自定义 DNS 解析器来处理使用 node-fetch 的 Nodejs 请求。我认为这里有一个解释的明星:节点覆盖请求 IP 解析,但我无法使其适用于任何请求。我的目标是使用替代 DNS 解析器,例如 cloudflare (1.1.1.1) 或 Google 公共 DNS (8.8.8.8),而不是操作系统/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")
})

Run Code Online (Sandbox Code Playgroud)

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

Som*_*one 6

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

Run Code Online (Sandbox Code Playgroud)