Nodejs http请求不工作

我有一段代码,应该做一个HTTP请求。 程序成功退出没有错误,但我没有看到任何反应,它甚至没有进入callback函数! 起初我以为这是因为HTTP是asynchronous的,并在最后放置一个大循环,但也没有工作。 有谁知道这个问题? 只有第一个控制台日志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"); } } 

更新

在OP收到响应之前,咕task任务终止; 添加async和callback到任务修复它。


如果我把你的代码放在这个函数之外,并且var http = require('http'); 我得到了一个响应直到222 ,在这一点上,它与SyntaxError: Unexpected token < 。 这是实际上死亡,因为你试图parsing一个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");