代码:
var http = require('http'), url = require('url'),
urls = 'http://127.0.0.1:81/';
var u = url.parse(urls), p = u['port'] ? u['port'] : 80;
http.get({
host: u['host'],
port: p,
path: u['path']
},
function(res){
if (res.statusCode == 200){
res.setEncoding('utf8');
res.on('data', function (chunk) {
log(urls+":\n" + chunk);
});
}else{
log(urls+":\n" + res.statusCode);
}
}
).on('error', function(e){
log("Got error: " + e.message);//这里报getaddrinfo ENOENT
});
在sh下用wget http://127.0.0.1:81/一切正常
在node不加81端口,也一切正常
2 回复
解决了,唉,造孽
如果url有端口,解析完后u[‘host’]里面也包含着,他里面的值是127.0.0.1:81,我还以为是127.0.0.1,这样写就可以了:
var u = url.parse(urls), p = u['port'] ? u['port'] : 80, h = u['host'].split(':');
h = h[0];
log(h);
log(p);
http.get({
host: h,
port: p,
path: u['path']
},
我也碰到了这个问题,我也补充一点,以免下次还有人遇到类似的情况,也多个思路 req就是http.request或get返回的httpClientRequest对象 req.on("error",function(err){ console.log(err); //如果这里也得到以下错误 { [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND’, errno: 'ENOTFOUND’, syscall: ‘getaddrinfo’ } });
有可能是你的options的host加了http了,host是不需要http,本机直接localhost或 127.0.0.1,如下: var options={ host:’localhost’, method:’POST’, port:8080, path:’/aa/bb/cc’, headers:{ 'Content-Type’:"application/x-www-form-urlencoded", 'Content-Length’:20 } };