【发布时间】:2018-10-26 22:56:17
【问题描述】:
我正在尝试从 iex api 获取 json 数据。我正在使用 googles dialogflow 的内联编辑器,当尝试从 api 获取 json 时,我不断收到错误消息:
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)
控制台日志显示我正在请求获取 json 请求的正确路径(在这种情况下,我需要 microsoft json 信息
API Request: api.iextrading.com/1.0/stock/MSFT/company
我不确定为什么没有正确读取 json,但我认为发生错误是因为我的代码的主体 var 没有从 http 请求接收信息。我只是不确定我的代码有什么问题。
这是我的代码:
'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();
});
});
});
}
【问题讨论】:
标签: javascript json parsing request dialogflow-es