Celaro
Celaro

Reputation: 226

Error: connect ECONNREFUSED. Unhandled 'error' event NodeJS

I am encountering the Nodejs error ECONNREFUSED 127.0.0.1:3000 when I try to send a get request to load a static file. I have seen many questions on this error but apparently there is no straight answer as to why this error is thrown. Here below is the code I have. I have tried changing localhost to 127.0.0.1 or change port numbers 3000, 7000, 8080 but nothing resolved it. Can someone please advised? Thank you.

//Basic web client retrieving content of file using get request

var http = require('http');

//options for request 

var options = {

hostname: 'localhost',
port: '3000',
path: '../html/hello.html'

};

//function to handle response from request

  function getResponse(response){

  var serverData='';

  response.on('data', function(chunk){

     serverData += chunk;
  });

   response.on('end', function(){

      console.log(serverData);
   });
 };

  http.request(options, function(response, error){

  getResponse(response);

}).end();

Upvotes: 2

Views: 9982

Answers (2)

sreepurna
sreepurna

Reputation: 1662

Your client code is good enough to work. You are getting the ECONNREFUSED because there is a no server which is listening to the particular port number and the Server is not sending any data and you are requesting to get data from the server and accumulate it.

Here is the sample code:

//Requesting for http and fs modules
var http = require('http');
var fs = require('fs');

//creating the server and reading the file synchronously
var server = http.createServer(function(req, res) {
    res.end(fs.readFileSync('./html1.html'));
}).listen(3000);

//creating the client which connects to local host at port number 3000
var options = {
    hostname: 'localhost',
    port: '3000',
}

//getting the data from server, storing it in to a variable, and printing at end of the data
function getResponse(response){
    var serverData='';
    response.on('data', function(chunk){
            serverData += chunk;
    });
response.on('end', function(){
            console.log(serverData);
    });
};

http.request(options, function(response, error){
    getResponse(response);
}).end();

Upvotes: 6

Shekhar Tyagi
Shekhar Tyagi

Reputation: 1674

the issue in your code , that you are not handling error, for this you have to handle error first.

var http = require('http');
    var options = {
    hostname: 'localhost',
    port: '3000',
    path: '../html/hello.html'
    };
      function getResponse(response){
    var serverData='';

      response.on('data', function(chunk){
         serverData += chunk;
      });

       response.on('end', function(){
    console.log(serverData);
       });
     };

      http.request(options, function(error , response){
    if(error){
    console.log(error);//handle error here.
    }else{
      getResponse(response);
    }}).end();

Upvotes: 0

Related Questions