简体   繁体   中英

Nodejs - DNS.Lookup is Rejecting URLs with HTTP?

I'm trying to build an Api in Nodejs that takes a URL and checks that it's a valid website.

Right now the dns.lookup rejects any invalid URLs (fake websites), and accepts any valid URLs as long as they don't start with HTTP:// or HTTPS:// . That's problematic because valid URLs are being rejected.

So this URL produces the "No Errors" message:

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

And this URL with HTTPS produces the "Errors" message:

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

The console.log output:

Errors: Error: getaddrinfo ENOTFOUND http://www.google.ca/ -- undefined -- undefined

Is there a way to configure the dns.lookup to accept URLs that start with HTTP or HTTPS?

dns.lookup takes a hostname. Protocols are not part of a hostname, so they shouldn't be passed in. Just remove the http/https from the URL via regex, before passing it to the dns.lookup function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM