Node.js unhandled 'error' event

2019-03-14 08:07发布

I have written a simple code and save it in file 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

5条回答
Rolldiameter
2楼-- · 2019-03-14 08:14

For me, the problem was another instance was running. Search for other node instance running and kill it. It should resume properly after.

查看更多
做自己的国王
3楼-- · 2019-03-14 08:18

This is happening because nothing is listening on localhost:8080. Here are the examples how to handle request errors How to catch http client request exceptions in node.js

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-14 08:19

Another server is running on same port 8080, so you need to kill and start your instance.

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

$ kill -9 28207

start instance

$ node server.js 
查看更多
等我变得足够好
5楼-- · 2019-03-14 08:25

Another server is running on the same port 8080 so change the port in this code or kill the port 8080 and restart it.

查看更多
我想做一个坏孩纸
6楼-- · 2019-03-14 08:27

change port number. Because your port is already is running.

port number like : 8000,8001,3000,3001,8080 ....

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

(or) Kill your port number. If you are using Ubuntu OS to follow this steps.

  1. To Find PID or TCP using terminal using this command: sudo netstat -ap | grep :"port number"
  2. To Kill the process using this command: kill -9 "process_id or tcp_id"
  3. To Run your NodeJs
查看更多
登录 后发表回答