javascript - 尝试从 api 获取 json 时解析错误 - 对话框流
问题描述
我正在尝试从 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 没有被正确读取,但我认为发生错误是因为我的代码的 body 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();
});
});
});
}
解决方案
推荐阅读
- python - 未触发扩展上下文菜单中的 Qaction 快捷方式
- javascript - 基于表单字段验证添加类
- reactjs - React Hooks (Functional) Lifecycle: 在 useEffect() 代码之前渲染的组件
- amazon-web-services - 是否可以知道 S3 存储桶中的平均请求量?
- rust - 如何在极地加载数据框时定义列类型?
- r - 尝试使用线性模型函数 lm() 时出错
- django - 如何处理组之间的数据流?(姜戈)
- python - Python 在另一个 Python .py 文件中定义一个类方法
- html - 使用 Leaflet Search 插件搜索 Shapefile
- python - ImportError 与 keras.preprocessing