Reputation: 2115
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:
And to my understanding, to access data in normalizedInput
, I'd do chunk.normalizedInput
, right? Why is it returning undefined?
Upvotes: 0
Views: 64
Reputation: 4678
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);
});
});
Upvotes: 1