Search code examples
node.jshttp-errornpm-request

Error: ESOCKETTIMEDOUT but doesn't seem to be DNS like other SO posts suggest


I am having some issues with the npm request package and getting it to call any URL properly unless the URL is to a server that is off. Example, I can't call amazon.com but I can call dev.personalDomain.com which points to an EC2 instance that is off entirely.

I tried to strip out the application logic to make it so that just the error is produced.

For this example assume monitor.body.url = 'amazon.com' is a string

My code

request({url: `http://${monitor.body.url}`, timeout: 20}, function (error, response, body) {
    console.log(`Response: ${response}`);
    console.log(`Body: ${body}`);
    console.log(`Error: ${error}`);
    if(error == 'ENOTFOUND' || error == 'ETIMEDOUT') {
      response.statusCode = 500;
  }
  if(error || response.statusCode < 200 && response.statusCode > 299 || !response.statusCode) {
    if(!response || !response.statusCode)  response.statusCode = 500;

    // Application logic

  }
  // If nothing went wrong just console.log -- This is used for debugging not useful in prod
  if(!error || response.statusCode > 299 || response.statusCode < 200)console.log(`Successfully called ${monitor.body.url}`);

});

Error message

Response: undefined
Body: undefined
Error: Error: ESOCKETTIMEDOUT
/home/ec2-user/environment/service/app.js:91
          if(!response || !response.statusCode)  response.statusCode = 500;
                                                                     ^

TypeError: Cannot set property 'statusCode' of undefined

I went looking on google/SO and came across that it might be DNS causing the issue and to test/resolve that I use:

const dns = require("dns");
dns.setServers(['8.8.8.8', '1.1.1.1']);

This made no change on the result of the request from above.

Does anyone have a suggestion or idea on what this might be? I am having no luck finding an example that is close and produces the same error message.

EDIT**

My DNS is perfectly fine on my dev machine so zero issues there. Also I didn't have this issue when I had just request({'http://${monitor.body.url}', function (error, response, body) { so seems like the error with how I am using request


Solution

  • Figured out the issue. My edit gives and an idea of what it might be... So the timeout I am using with Request is actually in milliseconds not seconds like I thought it was. So it was timing out after 20 milliseconds which was resulting in an error where not even the DNS was finishing properly. I changed it to actually be 20 seconds and the issue seems resolved.