我正在尝试从iex api获取json数据。我正在使用googles对话流的内联编辑器,当我试图从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变量没有接收到来自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();
});
});
});
}
发布于 2018-10-27 00:00:23
如果您正在使用内联对话流编辑器,那么您正在运行Firebase的Cloud Functions (或Firebase Cloud Functions)。默认情况下,基本计划上有一个限制,即您不能在Google的网络之外进行网络呼叫。
要解决此问题,您可以将您的Firebase套餐升级为订阅,如Blaze Plan。这确实要求在文件中有信用卡,但是基本使用级别应该是免费级别的一部分。
您也可以在其他任何地方运行您的webhook,只要有一个web服务器具有有效的SSL证书,可以处理HTTPS请求。如果你想在本地运行它,你甚至可以使用像ngrok这样的东西。
https://stackoverflow.com/questions/53017233
复制相似问题