我有一段代码应该做一个http获取请求。程序成功退出没有错误,但我没有看到任何回应,它甚至没有进入回调函数!起初我以为这是因为http是异步的,并且最后放了一个大的循环,但是这也不起作用。有谁知道这个问题?只有第一个控制台日志sendHttpRequest和444被打印。我也尝试了http.get,但它也没有工作。Nodejs的http请求不起作用
function sendHttpRequest (url, callBack) {
console.log("sendHttpRequest");
//constrct options
var options = {
host: 'www.google.com',
path: '/index.html',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
});
var req = http.request(options, function(res) {
console.log("333");
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("DATATATAT!")
output += chunk;
});
res.on('end', function() {
console.log('222');
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");
}
}
有人说谷歌没有“/指数.html“,我删除了它,但仍然无效。它只是没有进入回调。没有反应。 – user3084182
你打这个电话过得怎么样?这有几个问题,但除此之外,我可以看到所有的'console.log',并且回调函数也被调用。你也返回HTML,'JSON.parse'永远不会工作。 – matth
@ making3嗨,我把它封装成一个模块,并从一个咕task任务中调用它,但不知何故,我只能看到第一个控制台日志和最后一个,它是444.我必须在grunt或这个模块中调用异步等待回应?谢谢!对于json部分,原本我打算解析一个json,这样不会有问题。 – user3084182