getting Error: getaddrinfo ENOTFOUND while performing rest api call in node.js using http.request

Ashish Patel picture Ashish Patel · Nov 22, 2019 · Viewed 10.1k times · Source

i have created api in node.js which consume set of api hosted at http://dev.abc.co.in:20081 not every time but randomly sometimes it throws the error

Error: getaddrinfo ENOTFOUND dev.abc.co.in
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) {
  errno: 'ENOTFOUND',
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'dev.abc.co.in'
}

to call those api i have used request node module because i started getting this error i switched to fetch-node npm module and finally replace the code with internal node module http but getting same error

here is the code i have written using http.request

try{
    const options = {
        hostname: "dev.abc.co.in",
        port : 20081,
        path: "/api/entity/workorder",
        method: Config.method
    };

    if(Config.headers){
        options.headers = Config.headers
    }

    const req = http.request(options, (res) => {

        let data = '';
        res.on('data', (chunk) => {
            data += chunk;
        });
        res.on('end', () => {

            callback(res, data);
        });
        req.socket.destroy();
      }).on("error", (err) => {
        console.log("===Error: ", err);
        callback(null, err);
      });

      if(Config.method!="GET" && Config.body){
        Config.headers["Content-Length"] = Config.body.length;
        req.write(Config.body);
      }

      req.end();
    }catch(e){
        console.log("Exception=====",e);
    }

as shown in error message issue related to DNS so i try to resolve this DNS using node -pe 'require("dns").lookup("dev-vsg.dovertech.co.in",function(){console.dir(arguments)}) but still not resolved.

Answer

MEDZ picture MEDZ · Nov 22, 2019

1) Omit 'http://' from the beginning of your demain and all slashes from the end or any path after the actual domain.

2) Try to resolve your hostname:

const dns = require('dns');

dns.resolve("testdomain.com", 'ANY', (err, records) => {
  if (err) {
    console.log("Error: ", err);
  } else {
    console.log(records);
  }
});

If dns records has been returned, then you will know it's a node js problem and after that we can investigate further. If not, then it's a domain configuration issue.