从 NodeJS 运行 localhost 服务器时出现 ECONNREFUSED

Gue*_*875 5 javascript localhost node.js econnrefused

我在本地计算机上启动并运行了一个 NodeJS 服务器,该服务器正在侦听端口 50000。从另一台也在我的本地计算机上运行的服务器,我需要向该服务器发出一个简单的 GET 请求,但我得到的只是一个ECONNREFUSED 错误:

{ 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 }
Run Code Online (Sandbox Code Playgroud)

我的请求如下所示,使用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 ...
Run Code Online (Sandbox Code Playgroud)

我知道服务器已启动并正在运行,并且端点已定义,因为我可以在邮递员或浏览器中对完全相同的 url 发出请求并获得响应,但不知何故不在我的 NodeJS 代码中。

有人有主意吗?

김예군*_*김예군 12

正如评论的那样,将“localhost”更改为“http://127.0.0.1:50000”对我有用。我将在此处留下一个链接,以获取对此问题的可能解释

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


Shu*_*ora 5

在代码的开头使用它:

const dns = require('dns');

// Set default result order for DNS resolution
dns.setDefaultResultOrder('ipv4first');
Run Code Online (Sandbox Code Playgroud)


Moh*_*ari 3

可能的问题是其他进程已经在您尝试使用的同一端口上运行,请更改端口或终止端口上的现有进程。要终止端口上的进程,您可以尝试:

对于苹果电脑:

sudo kill $(lsof -t -i:8000) 
# or 
sudo fuser -k -n tcp 8000 
# or 
fuser -k 8000/tcp
Run Code Online (Sandbox Code Playgroud)

对于 Windows 检查这个

希望这可以帮助 :)