首页 > 解决方案 > 尝试从 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();
      });
    });
  });
}

标签: javascriptjsonparsingrequestdialogflow-es

解决方案


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

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

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


推荐阅读