Reputation: 1808
I am making a request to an api using node and the request package. I am trying to break up the body, however I noticed that the body of the request is coming back as a string. I'm not sure why this is considering I am using this api elsewhere in my projects and everything works fine. Any ideas as to why this might be happening or how to handle it (assuming it's not an api specific problem)?
If it helps I am using the IEX API for stock data...
Here is my code:
request('https://api.iextrading.com/1.0/tops/last?symbols=SNAP', (err, res, body) => {
if(err) {
return console.error(err);
}
const stockMoment = new StockMoment({
symbol: body.symbol,
price: body.price,
time: body.time,
});
stockMoment.save((err) => {
if(err) return handleError(err);
console.log('Saved!');
});
console.log(typeof body); // Tells me it's a string
});
Upvotes: 2
Views: 483
Reputation: 30400
My understanding is that you need to provide an additional json
parameter request()
, so that the response is automatically parsed from a JSON string, to an equivalent JSON object.
Something like this should do the trick:
request({
url : 'https://api.iextrading.com/1.0/tops/last?symbols=SNAP',
// [ADD] parameter json : true
json : true
}, (err, res, body) => {
if(err) {
return console.error(err);
}
const stockMoment = new StockMoment({
symbol: body.symbol,
price: body.price,
time: body.time,
});
stockMoment.save((err) => {
if(err) return handleError(err);
console.log('Saved!');
});
console.log(typeof body); // Tells me it's a string
});
Upvotes: 3