Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with "Unhandled 'error' event" error - NodeJS

I am trying to get hands on Node.js. Here is the very simple code I was playing with

var http = require('http');
http.get('www.google.com', function(res) {
  console.log(res.statusCode);
});

I got the following error upon running this code

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:80
    at Object.exports._errnoException (util.js:837:11)
    at exports._exceptionWithHostPort (util.js:860:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)

upon reading the error output, I added two more lines of code to handle error event like below

var http = require('http');
http.get('www.google.com', function(res) {
  console.log(res.statusCode);
  res.on('error', function(error) {
    console.error(error);
  });
});

but the same error message was still persisting, where am I messing it up?

like image 971
segmentationfaulter Avatar asked Mar 15 '23 17:03

segmentationfaulter


1 Answers

You must use a URL and not a domain name in http.get unless you specify options as an object:

options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

Compare:

var http = require('http');
http.get('http://www.google.com/', function(res) {
  console.log(res.statusCode);
});

With:

var http = require('http');
http.get({host:'www.google.com'}, function(res) {
  console.log(res.statusCode);
});

Both of those work.


Note I thought that it was a network issue at first but actually what happened the default for host in the options is localhost so that when it failed to parse the string and was left with the default options. As if the code had been:

var http = require('http');
http.get({}, function(res) {
  console.log(res.statusCode);
});
like image 186
Dan D. Avatar answered Mar 17 '23 05:03

Dan D.