I am currently working on retrieving JSON data from the iex API. Utilizing Google's Dialogflow inline editor, I encountered an error while attempting to fetch the JSON information:
Error: Parse Error
at Error (native)
at Socket.socketOnData (_http_client.js:363:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:559:20)
Upon checking the console log, it appears that I have correctly specified the path for the desired JSON request (in this case, Microsoft JSON details).
API Request: api.iextrading.com/1.0/stock/MSFT/company
The issue seems to arise from my code's inability to properly read the JSON file, possibly due to a lack of information being received by the 'body' variable during the HTTP request process. I am uncertain about what exactly might be causing this error.
Displayed below is the code snippet in question:
'use strict';
const http = require('http');
const functions = require('firebase-functions');
const host = 'api.iextrading.com';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) => {
// Get the company
let company = req.body.queryResult.parameters['company_name']; // city is a required param
// Call the iex API
callCompanyApi(company).then((output) => {
res.json({ 'fulfillmentText': output });
}).catch(() => {
res.json({ 'fulfillmentText': `I don't know this company`});
});
});
function callCompanyApi (company) {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the company
let path = '/1.0/stock/' + company + '/company';
console.log('API Request: ' + host + path);
// Make the HTTP request to get the company info
http.get({host: host, path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; });// store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
console.log(body);
let response = JSON.parse(body);
let description = response['description'];
// Create response
let output = `${description}`
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
console.log(`Error calling the iex API: ${error}`)
reject();
});
});
});
}