4

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?

0

1 Answer 1

7

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.