Search code examples
node.jshttpget

ENOTFOUND error when using http.request() but http.get() working


I have this strange error with NodeJS where I am trying to do a simple GET request. This works for me:

   http.get('http://54.241.239.69:8332/', function(res){
            var str = '';
            res.on('data', function (chunk) {
                   str += chunk;
             });

            res.on('end', function () {
                 //console.log(str);
                 clientRes.send(str);
            });
      });

However, when trying to do the same with a request like this:

const options = {
    hostname: 'http://54.241.239.69',
    port: 8332,
    path: '/',
    method: 'GET'
  }

  const req = https.request(options, (res) => {
    console.log(`statusCode: ${res.statusCode}`)

    res.on('data', (d) => {
      process.stdout.write(d)
    })
  })

  req.on('error', (error) => {
    console.error(error)
  })

  req.end()

it gives me a Error: getaddrinfo ENOTFOUND http://54.241.239.69 http://54.241.239.69:8332 error.

Why does get() works but not request()? Thank you.


Solution

  • hostname doesn't take protocol. So it will be just 54.241.239.69.

    Also, you may need to change https module to http as your link is has http protocol.

    const options = {
        hostname: '54.241.239.69',
        port: 8332,
        path: '/',
        method: 'GET'
    }
    

    Note: ENOTFOUND is a DNS error, that means it cannot resolve the hostname.