How To Deal With Error "Unprocessed Error" "Error" - NodeJS

I am trying to get Node.js. Here is the easiest code I've played with

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

I got the following error while 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)

after reading the error output, I added two more lines of code to handle the error event, as shown below

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

but the same error message still persisted, where did I mess it up?

+4
source share
1 answer

You should use the URL, not the domain name http.get, unless you specify optionsas an object:

optionsmay be an object or a string. If optionsis a string, it is automatically parsed using url.parse().

:

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

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

.


. , , , host , localhost, , . :

var http = require('http');
http.get({}, function(res) {
  console.log(res.statusCode);
});
+6

Source: https://habr.com/ru/post/1608180/


All Articles