Javascript 如何处理“未处理的'错误'事件”错误 - NodeJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32675907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to deal with "Unhandled 'error' event" error - NodeJS
提问by segmentationfaulter
I am trying to get hands on Node.js. Here is the very simple code I was playing with
我正在尝试使用 Node.js。这是我正在玩的非常简单的代码
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?
但同样的错误信息仍然存在,我在哪里搞砸了?
回答by Dan D.
You must use a URL and not a domain name in http.get
unless you specify options
as an object:
http.get
除非您指定options
为对象,否则您必须使用 URL 而不是域名:
options
can be an object or a string. Ifoptions
is a string, it is automatically parsed withurl.parse()
.
options
可以是对象或字符串。如果options
是字符串,则自动解析为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:
请注意,我起初认为这是一个网络问题,但实际上host
选项中的默认设置是localhost
这样,当它无法解析字符串并保留默认选项时。好像代码是:
var http = require('http');
http.get({}, function(res) {
console.log(res.statusCode);
});