HOW TO FIX “ENOTFOUND” ERROR IN NODE.JS

The ENOTFOUND exception occurs in Node.js when a connection cannot be established to some host due to a DNS error. This usually occurs due to an incorrect host value, or when localhost is not mapped correctly to 127.0.0.1. It can also occur when a domain goes down or no longer exists

If we get this error in your Node.js application, we can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You can also use a tool like DNS Checker to confirm that the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard library, ensure that the host value in the options object contains only the domain name or IP address of the server. It shouldn’t contain the protocol, port, or request path (use the protocol, port, and path properties for those values respectively).

// don't do this//
const options = {
  host: 'http://example.com/path/to/resource',
};

// do this instead//
const options = {
  host: 'example.com',
  path: '/path/to/resource',
};

http.request(options, (res) => {});

Check your localhost mapping

If you’re trying to connect to localhost, and the ENOTFOUND error is thrown, it may mean that the localhost is missing in your hosts file. On Linux and macOS, ensure that your /etc/hosts file contains the following entry:

/etc/hosts

127.0.0.1   localhost

You may need to flush your DNS cache afterward:

sudo killall -HUP mDNSResponder # macOS

Leave a comment

Your email address will not be published. Required fields are marked *