Encountered a parsing issue while attempting to retrieve JSON data from an API in Dialogflow

I am currently working on retrieving JSON data from the iex API. Utilizing Google's Dialogflow inline editor, I encountered an error while attempting to fetch the JSON information:

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)

Upon checking the console log, it appears that I have correctly specified the path for the desired JSON request (in this case, Microsoft JSON details).

API Request: api.iextrading.com/1.0/stock/MSFT/company

The issue seems to arise from my code's inability to properly read the JSON file, possibly due to a lack of information being received by the 'body' variable during the HTTP request process. I am uncertain about what exactly might be causing this error.

Displayed below is the code snippet in question:

'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();
      });
    });
  });
}

Answer №1

When utilizing the Inline Dialogflow Editor, your system is powered by Cloud Functions for Firebase (or Firebase Cloud Functions). The default base plan comes with a restriction that limits making network calls beyond Google's network.

To work around this limitation, you have the option to upgrade your Firebase plan to a subscription like the Blaze Plan. This may require adding a credit card to your account, but the basic level of usage remains within the free tier.

Alternatively, you can choose to host your webhook in any other location as long as there is a web server equipped with a valid SSL certificate capable of handling HTTPS requests. If running it locally is preferable, tools like ngrok can be utilized.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top method for transferring server (C# / Razor) data to an AngularJS application

In our use of DNN, we often encounter the need to pass specific context values (such as page id or module-on-page-id) into an AngularJS application. While we have established our own conventions for achieving this, we are interested in hearing about how ot ...

What steps should I take to securely store my WordPress form submission data in a JSON file?

I recently set up a form on my AWS Wordpress site using NinjaForms and I'm looking for a way to save the data collected into a JSON file. The form functions correctly, but I need a plugin that can assist with this task. If anyone could point me in th ...

VueJS form validation does not account for empty inputs in both fields

One of the challenges I'm facing is generating a form with Vue.js using the input fields below: { name: 'first_name', type: 'text', label: 'First Name', placeholder: 'First Name', ...

Refreshing a particular <div> on a webpage while making an AJAX request

I've encountered an issue that has left me stuck. The problem is that I need to refresh a specific div on my page that contains PHP script. Below is the JavaScript function causing trouble: function select_dayoff() { jQuery('#loader').c ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

Convert a JSON Object using AngularJs

Is there a method in Angular to restructure this JSON Object? I am looking to convert the JSON object from its original format: $scope.TestJson = { "filters": [ { "dataPropertyID": "VoidType", ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...

I am trying to figure out how I can include "all types of JSON data" in my typed request model when using a REST API. Can anyone

In my current project, I am utilizing .NET Framework and ASP.NET Core to develop a RESTful web API. This particular web api includes a method for receiving a request model to store information, as well as another method for later retrieving that data. Th ...

Unexpected Errors Occurring on CRM 2016 Forms

Ever since our upgrade from CRM 2011 to CRM 2016, we've been encountering random script error messages during form loading. Despite properly including all dependency scripts in the form properties, we haven't been able to resolve the issue. I cam ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

Creating a script that automatically launches the terminal and executes specific commands

Can anyone help me with creating a file that, when clicked on, opens a command prompt and executes the following commands? cd desktop\discordBOT node . Many thanks in advance! ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

HTML5 enables the creation of an imperceptible scrollbar

I am looking to make my scrollbar invisible without it being visible however, I still want it to function when hovering over the box Also, I need it to work smoothly on both tablets and computers, which is why I have opted for using html5 I would great ...

Issue with displaying dates correctly when retrieving data from an external CSV using Highcharts (Highstock)

I have been struggling for several days to integrate Highstock with an external CSV file. Initially, the problem was that the imported data was sorted in "descending" order while Highcharts required it to be sorted in "ascending" order. After discovering a ...

The @ViewChild in Angular 2 seems to be unable to detect the BaseChartDirective from the ng2-charts

I'm currently using ng2-charts v1.5.0 and I'm facing an issue with updating the chart data after a click event. Despite following suggestions from other sources, I am unable to get it to work properly. Here is a snippet of my code: <div styl ...

Rejuvenate a just-launched window.open starting from the about:blank

After receiving data from an ajax result, I am trying to open a pdf in a new window. However, the pdf viewer is only displayed if I manually resize the window (using manual hotspot resizing). How can I ensure that the contents display properly in its popu ...