【发布时间】: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 构建而不是外部模块