获取https响应的正文

时间:2016-01-20 15:54:14

标签: javascript node.js

我是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文件的字符串,但问题是当我尝试将它保存在一个名为body的变量中时,当我打印出来时,什么都没有出现! :

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.');

    });
});

我希望我的问题足够明确。如果不明确,请询问澄清。

1 个答案:

答案 0 :(得分:1)

您在触发data之前正在打印正文变量。

尝试如下。

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