Nodejs - DNS.Lookup 拒绝使用 HTTP 的 URL?

Ada*_*ler 0 javascript lookup dns http node.js

我正在尝试在 Nodejs 中构建一个 Api,它接受一个 URL 并检查它是否是一个有效的网站。

现在 dns.lookup 拒绝任何无效 URL(虚假网站),并接受任何不以 HTTP:// 或 HTTPS:// 开头的有效 URL。这是有问题的,因为有效的 URL 会被拒绝。

因此,此 URL 会生成“无错误”消息:

dns.lookup('www.google.ca', function onLookup(err, address, family) 
  if (err == null) {
    console.log ('No Errors: ' + err + ' - ' + address + ' - ' + family) 
  } else {
    console.log ('Errors: ' + err + ' -- ' + address + ' -- ' + family)
  }
});
Run Code Online (Sandbox Code Playgroud)

这个带有 HTTPS 的 URL 会产生“错误”消息:

dns.lookup('https://www.google.ca/', function onLookup(err, address, family) 
  if (err == null) {
    console.log ('No Errors: ' + err + ' - ' + address + ' - ' + family) 
  } else {
    console.log ('Errors: ' + err + ' -- ' + address + ' -- ' + family)
  }
});
Run Code Online (Sandbox Code Playgroud)

console.log 输出:

错误:错误:getaddrinfo ENOTFOUND http://www.google.ca/ -- 未定义 -- 未定义

有没有办法配置 dns.lookup 接受以 HTTP 或 HTTPS 开头的 URL?

Fra*_*erZ 6

dns.lookup需要一个主机名。协议不是主机名的一部分,因此不应传入它们。只需通过正则表达式从 URL 中删除 http/https,然后再将其传递给函数即可dns.lookup

const url1 = 'https://google.ca';
const url2 = 'google.com';

const REPLACE_REGEX = /^https?:\/\//i

const res1 = url1.replace(REPLACE_REGEX, '');
const res2 = url2.replace(REPLACE_REGEX, '');

console.log(res1);
console.log(res2);

// dns.lookup(res1...);
Run Code Online (Sandbox Code Playgroud)