Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  191] [ 1]  / answers: 1 / hits: 26805  / 9 Years ago, sun, september 20, 2015, 12:00:00

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?


More From » node.js

 Answers
23

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);
});

[#64995] Thursday, September 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinal

Total Points: 655
Total Questions: 99
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;