【问题标题】:Use Custom DNS resolver for any request in NodeJS对 NodeJS 中的任何请求使用自定义 DNS 解析器
【发布时间】:2022-02-11 12:11:17
【问题描述】:

我正在寻找一种方法,通过 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 模块并设置一个自定义服务器。

【问题讨论】:

  • staticDnsAgent 旨在提供域的 IP,因此在您的示例中,api.github.com 被解析为 1.1.1.1。相反,使用 github.com/sc0Vu/doh-js-client 解析并使用 staticDNSAgent 中的结果
  • 感谢@Martheen 我能够取得结果,请参阅下面的答案。我在 dns 模块中使用 nodejs 构建而不是外部模块

标签: node.js dns


【解决方案1】:

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

【讨论】:

  • return new httpModule.Agent({ lookup: staticLookup() }); 应该是`return new httpModule.Agent({lookup: staticLookup});`
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2015-02-23
  • 2012-06-15
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多