简体   繁体   English

Node.js 未处理的“错误”事件

[英]Node.js unhandled 'error' event

I have written a simple code and save it in file try.js .我编写了一个简单的代码并将其保存在文件 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.");

When I run it through terminal it give an error当我通过终端运行它时,它会出错

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

For me, the problem was another instance was running.对我来说,问题是另一个实例正在运行。 Search for other node instance running and kill it.搜索正在运行的其他节点实例并杀死它。 It should resume properly after.之后它应该可以正常恢复。

This is happening because nothing is listening on localhost:8080.发生这种情况是因为没有在 localhost:8080 上监听。 Here are the examples how to handle request errors How to catch http client request exceptions in node.js以下是如何处理请求错误的示例 如何在 node.js 中捕获 http 客户端请求异常

Another server is running on same port 8080, so you need to kill and start your instance.另一台服务器在同一端口 8080 上运行,因此您需要终止并启动您的实例。

find running instance查找正在运行的实例

$ 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    

kill existing server instance using pid使用 pid 杀死现有的服务器实例

$ kill -9 28207

start instance启动实例

$ node server.js 

change port number.更改端口号。 Because your port is already is running.因为您的端口已经在运行。

port number like : 8000,8001,3000,3001,8080 ....端口号如:8000,8001,3000,3001,8080 ....

 app.listen(3030,()=>{})

(or) Kill your port number. (或)杀死您的端口号。 If you are using Ubuntu OS to follow this steps.如果您使用的是 Ubuntu 操作系统,请按照以下步骤操作。

  1. To Find PID or TCP using terminal using this command: sudo netstat -ap |使用以下命令使用终端查找 PID 或 TCP: sudo netstat -ap | grep :"port number" grep :"端口号"
  2. To Kill the process using this command: kill -9 "process_id or tcp_id"要使用此命令终止进程: kill -9 "process_id or tcp_id"
  3. To Run your NodeJs运行你的 NodeJs

另一台服务器正在同一端口 8080 上运行,因此更改此代码中的端口或终止端口 8080 并重新启动它。

A different process is already running in the same port.不同的进程已经在同一个端口中运行。 Either kill the running process or change the port number in the current code.要么终止正在运行的进程,要么更改当前代码中的端口号。 Your issue will be fixed!您的问题将得到解决!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM