获取 https 响应的正文

Getting the body of an https response

本文关键字:正文 响应 https 获取      更新时间:2023-09-26

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

使用上面的代码,我可以打印出 body,它应该是包含 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.');
    });
});

我希望我的问题足够清楚。如果模棱两可,请要求澄清。

您正在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