尝试从api获取json时解析错误-dialogflow

时间:2018-10-26 22:56:18

标签: javascript json parsing request dialogflow

我正在尝试从iex api获取json数据。我使用的是Google对话框流的内联编辑器,当尝试从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,但我认为发生了错误,因为我的代码的主体变量未从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();
      });
    });
  });
}

1 个答案:

答案 0 :(得分:0)

如果您使用内联对话框流编辑器,则说明您正在运行Firebase的Cloud Functions(或Firebase Cloud Functions)。默认情况下,基本计划有一个限制,即您不能在Google网络之外拨打网络电话。

要解决此问题,您可以将Firebase计划升级为诸如Blaze Plan之类的订阅。这确实需要使用信用卡,但是基本使用级别应该是免费套餐的一部分。

您还可以在其他任何地方运行Webhook,只要存在具有有效SSL证书的Web服务器即可处理HTTPS请求即可。如果要在本地运行,甚至可以使用类似ngrok的东西。