4

I have a NodeJS server up and running on my local machine that is listening to port 50000. From another server, that is also running on my local machine, I need to make a simple GET request to that server, but all I get is an ECONNREFUSED error:

{ Error: connect ECONNREFUSED 127.0.0.1:50000
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 50000 }

My request looks as follows, using request:

var options = {
    url: "http://localhost:50000",
    method: "GET"
}
request(options, function(error, response, body) {
    if (error) {
        console.log("[" + getDateTime() + "] Error connecting to localhost:");
        console.log(error);
        return;
   }
   // continue ...

I know that the server is up and running and that the endpoint is defined, because I can do the request to that exact same url in postman or in my browser and get a response, but somehow not in my NodeJS code.

Anybody have an idea?

Guest9875
  • 63
  • 1
  • 2
  • 8
  • 2
    Changing `localhost` to `http://127.0.01:50000` worked for me. I guess node wasn't respecting the hosts file on my Mac. – user Nov 15 '22 at 09:48

4 Answers4

7

Just as commented, changing "localhost" to "http://127.0.0.1:50000" worked for me. I ll leave a link down here for a possible explanation for this issue

https://github.com/node-fetch/node-fetch/issues/1624#issuecomment-1235826631

Petr Gazarov
  • 3,602
  • 2
  • 20
  • 37
김예군
  • 169
  • 2
  • 7
3

The possible issue is that some else process is already running on the same port you are trying to use, either change your port or kill the existing process on your port. To kill the process on port you can try:

For mac:

sudo kill $(lsof -t -i:8000) 
# or 
sudo fuser -k -n tcp 8000 
# or 
fuser -k 8000/tcp

And for windows check this

hope this helps :)

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26
2

You might be running both the servers on the same port, kill another server on same port.

If you're on linux, you can kill port using sudo fuser -k -n tcp 5000

or if you're using windows: taskkill /PID 5000 /F

sid
  • 365
  • 2
  • 11
2

Use this at the beginning of your code:

const dns = require('dns');

// Set default result order for DNS resolution
dns.setDefaultResultOrder('ipv4first');
Shubham Arora
  • 807
  • 9
  • 10
  • I was running into this just now on my Windows machine, found that 127.0.0.1:port did work for me, so I added these lines and now localhost works as well. I think without it, it was coming in as ::1 (IPv6) and my server-side wasn't handling that. But not sure of the actual cause, only that calling setDefaultResultOrder() did in fact fix it to support localhost. – Appurist - Paul W Aug 08 '23 at 20:42