我有一段应该执行http get请求的代码。程序成功退出没有错误,但我没有看到任何响应,它甚至没有进入回调函数!起初我认为这是因为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");
}
}
答案 0 :(得分:4)
<强>更新强>
在OP收到回复之前,grunt任务终止;添加async
和回调任务修复它。
如果我将代码移到函数之外并添加var http = require('http');
,我会在222
之前得到响应,此时它会以SyntaxError: Unexpected token <
消失。这实际上是因为你试图将HTML响应解析为JSON而死亡。
如果您粘贴下面的整个脚本并端到端地运行它,则控制台会以:
终止undefined:1
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
^
SyntaxError: Unexpected token <
at Object.parse (native)
at IncomingMessage.<anonymous> (/Users/you/nodetest/tmp/test.js:31:28)
at IncomingMessage.EventEmitter.emit (events.js:120:20)
at _stream_readable.js:896:16
at process._tickCallback (node.js:599:11)
剧本:
var http = require('http');
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');
// it's failing on the next line, because the output
// it's receiving from Google is HTML, not JSON.
// If you comment out this line and simply
// "console.log(output)" you'll see the HTML response.
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");