Node.js未处理的'错误'事件

ana*_*ana 30 javascript port http node.js express

我编写了一个简单的代码并将其保存在try.js文件中.

var http = require('http');
var makeRequest = function(message) {
  var options = {
    host: 'localhost', port: 8080, path: '/', method: 'POST'
  }
  var request = http.request(options, function(response){
    response.on('data', function(data){
      console.log(data);
    });
  });

  request.write(message);
  request.end();
}
makeRequest("Here's looking at you, kid.");
Run Code Online (Sandbox Code Playgroud)

当我通过终端运行它时会出错

throw er; // Unhandled 'error' event,
Error: connect ECONNREFUSED
at errnoException (net.js:884:11)
at Object.afterConnect [as oncomplete] (net.js:875:19)error' event
Run Code Online (Sandbox Code Playgroud)

MVC*_*man 43

对我来说,问题是另一个实例正在运行.搜索正在运行的其他节点实例并将其终止.它应该在之后正确恢复.


Dam*_*zyk 12

发生这种情况是因为没有任何东西在监听localhost:8080.以下是如何处理请求错误的示例如何捕获node.js中的http客户端请求异常


KAR*_*N.A 6

另一台服务器在同一端口8080上运行,因此您需要终止并启动您的实例.

找到运行实例

$ netstat -nlp | grep 8080

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp6       0      0 :::8881                 :::*                    LISTEN      28207/node    
Run Code Online (Sandbox Code Playgroud)

使用pid杀死现有服务器实例

$ kill -9 28207
Run Code Online (Sandbox Code Playgroud)

开始实例

$ node server.js 
Run Code Online (Sandbox Code Playgroud)