MLyck
MLyck

Reputation: 5765

node JSON https request becoming undefined

I am trying to send a single https request to an API, with a bunch of data in JSON format.

However, when running the code, I first ran into the problem that everything was undefined. I commented out my loop, trying to parse the data I needed, and right now I'm just trying to console.log all of the data.

However, it seems to still be looping through stuff somehow despite not having a loop anywhere in my code anymore.

here is the code for my request:

function getCards() {
  // make a request
  var options = {
    host: 'omgvamp-hearthstone-v1.p.mashape.com',
    path: '/cards',
    method: 'GET',
  };

  var req = https.request(options, function(res) {
    console.log('STATUS ' + res.statusCode);
    console.log('HEADERS ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function(data) {
      //console.log(data);
      updateCardsCollection(JSON.stringify(data));
    });
  });

  req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
  });

  req.end();
}

The weird thing is that the console.log(data) in the above code, logs out all of the data just fine.

function updateCardsCollection(data) {
  var cardsRaw = [];
  console.log("DATA");
  console.log("===========================================================");
  console.log(data.Classic);
}

Here "Classic" is one of the arrays of objects in the API.

Before implementing node, express, mongoose and jade. The following loop worked fine to parse through the data:

   for(var key in data) {
     for(var i = 0; i < data[key].length; i++) {
       console.log(data[key][i].cardId);

However the above beginning of a loop would print out an undefined error as well.

Another strange problem I seem to be having with this code is when I run it with the loop commented out, with just the 3 console.logs in the 'updateCardsCollection' function. It logs those 3 lines a lot of times. Despite the function only being called once.

Any idea why this code is no longer working for getting my API data?

Upvotes: 1

Views: 1662

Answers (1)

savelichalex
savelichalex

Reputation: 196

At first, you need to do JSON.parse instead of JSON.stringify while you try to update your collection, if you want work with objects, not with string.

But if you done with first, your code still not work, because in data handler you get chunked data, not full response. See https://nodejs.org/api/http.html#http_http_request_options_callback for it.

You must accumulate data like this:

const req = https.request(options, res => {
    const data = [];
    res.on('data', d => data.push(d));
    res.on('end', () => updateCardsCollection(JSON.parse(data.join(''))));
})

Upvotes: 4

Related Questions