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

标签 node.js dns

我正在寻找一种方法,使用 node-fetch 为 nodejs 请求使用自定义 DNS 解析器。我认为这里有一个解释的明星:Node override request IP resolution但我无法让它满足任何请求。我的目标是使用替代的 DNS 解析器,例如 cloudflare (1.1.1.1) 或 Google 公共(public) 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")
})

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

最佳答案

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

关于node.js - 对 NodeJS 中的任何请求使用自定义 DNS 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71074255/

相关文章:

javascript - 为什么这个 puppeteer 的异步函数语法?

asp.net - 电子邮件会进入垃圾邮件而不是收件箱

objective-c - Objective-C 中使用自定义 DNS 服务器进行 DNS 查找

redirect - 301重定向与 parking

docker 。将动态主机 ip 添加到容器上的 env var

browser - 为什么浏览器不使用 SRV 记录?

node.js - 如何使用sequelize隐藏链接查询中的关联表结果?

node.js - 我应该在哪里存储我的 Node.js 应用程序的 key ?

javascript - 通过 Grunt 将 JS 文件包含在另一个文件中,而不需要 Require.js

node.js - 使用聚合来组合两个字段