Search code examples
javascriptnode.js

Getting the body of an https response


I'm a newbie to nodejs, and I'm having a weird problem trying to get my response's body. well, for printing out the body we might do something like this, right? :

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

With the above code, I can print out the body, which is supposed to be a string containing a JSON file, but the problem is that when I try to save it in a variable called body, when I print that, nothing shows up! :

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

    });
});

I hope my question is clear enough. Please ask for clarification if it's ambiguous.


Solution

  • You are printing body variable before data got triggered.

    Try like below.

    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);
          console.log('No more data in response.');
    
        });
    });
    

    Refer:
    https://nodejs.org/api/https.html#https_https_get_options_callback