node.jsdnswindows-10requestjs

Why does NodeJS request() fail on localhost in flight mode, but not 127.0.0.1? (Windows 10)


Given I already have a server up and running on localhost (see further down for an example), at a node command line while online, I get the following:

> var x = request('http://localhost:8080/test.html',
...               function(err) { if (err) console.log(err) })
undefined
> 

I expect to get the above result all the time.

If I've switched to flight mode I get the following:

> var x = request('http://localhost:8080/test.html',
...               function(err) { if (err) console.log(err) })
undefined
> { Error: getaddrinfo ENOENT localhost:8080
    at Object.exports._errnoException (util.js:1022:11)
    at errnoException (dns.js:33:15)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'getaddrinfo',
  hostname: 'localhost',
  host: 'localhost',
  port: '8080' }

Trying this again with 127.0.0.1 instead of localhost works whether or not I'm in flight mode.

Question

Why does localhost not work? I can see it's something to do with Windows's DNS resolver.

Setup for the client code above

You need to install the require first:

C:\> npm install require

Broader context

I've boiled this down to the simplest I can. See Why does web-component-tester time out in flight mode? for the broader context.

Example server

The question isn't about the following server specifically, it's just a quick example. I think probably any local server would do, not just a NodeJS one. The problem is in the client code as detailed above.

Setup for the example server:

C:\> npm install connect serve-static

server.js:

var connect = require('connect')
var serveStatic = require('serve-static')
connect().use(serveStatic(__dirname)).listen(8080)

test.html:

<html>Really not important, but necessary for completeness</html>

Start the server:

C:\> node server.js

Solution

  • The solution is to install the Microsoft Loopback Adapter, as detailed below: