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?
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. Ifoptions
is a string, it is automatically parsed withurl.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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With