【发布时间】:2013-12-09 19:41:02
【问题描述】:
我有一段代码应该执行 http 获取请求。程序成功退出,没有错误,但我没有看到任何响应,甚至没有进入回调函数!一开始我以为是因为http是异步的,最后放了一个大循环,但这也没有用。有谁知道这个问题?只有第一个控制台日志 sendHttpRequest 和 444 被打印出来。我也尝试了 http.get 但它也不起作用。
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");
}
}
【问题讨论】:
-
有人说google没有“/index.html”,我把它删了还是不行。它甚至没有进入回调内部。没有回应。
-
你怎么称呼这个?这有一些问题,但除此之外,我会看到所有
console.log,并且还会调用回调函数。您还返回了 HTML,JSON.parse将永远无法工作。 -
@making3 嗨,我把它包装成一个模块并从一个 grunt 任务中调用它,但不知何故,我只看到第一个控制台日志和最后一个,即 444。我必须打电话grunt 或此模块中的异步等待响应?谢谢!对于 json 部分,本来我是要解析一个 json 的,这样就不会有问题了。
-
@making3 感谢 r3mus,我找到了问题所在。这是因为 grunt 任务在我得到 http 请求的响应之前就终止了。现在我添加了异步和回调来解决这个问题!也非常感谢您的帮助! :)