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

Nodejs - DNS.Lookup is Rejecting URLs with HTTP?

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

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

所以这个 URL 产生了 "No Errors" 消息:

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)
  }
});

并且此 URL 与 HTTPS 生成 "Errors" 消息:

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)
  }
});

console.log输出:

错误:错误:getaddrinfo ENOTFOUND http://www.google.ca/ -- undefined -- undefined

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

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...);