获取https响应的正文

我是nodejs的新手,我有一个奇怪的问题,试图得到我的回应的身体。 好吧,为了打印出身体,我们可以做这样的事情,对吧? :

var https = require('https'); var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){ //print the data response.setEncoding('utf8'); response.on('data', function (chunk){ console.log('BODY : ' + chunk); // Prints the body, no problem. }); response.on('end', function() { console.log('No more data in response.'); }); }); 

使用上面的代码,我可以打印出包含JSON文件的string,但问题是,当我试图将其保存在一个名为body的variables中时,当我打印时,什么都没有显示出来! :

 var https = require('https'); var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){ //save the data in a variable var body = ''; response.setEncoding('utf8'); response.on('data', function (chunk){ body += chunk; }); console.log(body); // prints nothing! response.on('end', function() { console.log('No more data in response.'); }); }); 

我希望我的问题很清楚。 如果不明确,请要求澄清。

data触发之前,您正在打印身体variables。

尝试如下。

 var https = require('https'); var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){ //save the data in a variable var body = ''; response.setEncoding('utf8'); response.on('data', function (chunk){ body += chunk; }); response.on('end', function() { console.log(body); // prints nothing! console.log('No more data in response.'); }); }); 

参考:
https://nodejs.org/api/https.html#https_https_get_options_callback