0

I'm doing a GET http request for Google Civic's API, where I'm providing an address and receiving members of the U.S. government based on where the provided address is located.

//var options has the host, path, etc.
var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log(chunk.normalizedInput) //returns 'undefined'
  });
});

chunk is printing this out:

enter image description here

And to my understanding, to access data in normalizedInput, I'd do chunk.normalizedInput, right? Why is it returning undefined?

1 Answer 1

1

You retrieve string by stream, you need to wait the end of the stream and parse the string before manipulate object

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  var chunks = [];
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
   chunks.put(chunk);
  });
  res.on('end', function () {
   console.log(JSON.parse(chunks.join("")).normalizedInput);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.