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

Cannot find JS variable after loop has completed

I am struggling to understand why the value of my variable is not changing in my function. Here is my code snippet: var count = function(datain){ let temparr = [], countobj = {}; $.each(datain, function(key, val) { console.log(temparr); cou ...

I am unable to input just one numerical value into my function

I am encountering an issue with my function that calls another function. The problem arises when inputting single numbers in the prompt; I have to append a letter like (a1, a2, a3) for it to function correctly. The function "PrintSelectedToPDF" works smoo ...

Display dynamic content in a div using ajax and add animation effects, along with a "back" button functionality

I am in the process of creating a fantasy NFL web app using bootstrap and jQuery. Initially, I opted for Framework7 due to its user-friendly native app interface but decided to shift towards building a fully responsive page instead. Within my project, the ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

I need assistance with the following issue: the type 'Observable<ArrayBuffer>' cannot be assigned to the type 'Observable<User[]>. Can anyone provide a solution for this problem?

Encountered an issue with the error message: Type 'Observable' cannot be assigned to type 'Observable<User[]>' while working on setting up Angular service.ts for implementing HTTP requests. ...

The script file (.js) isn't showing up on the PHP or HTML webpage

Experiencing a peculiar issue and seeking advice on alternative solutions due to my limited experience in this matter. The Issue: I currently have the following script running smoothly: <script type="text/javascript" id="myscript" src="http://piclau ...

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

How does the method of including JavaScript libraries in HTML differ from adding them as npm dependencies?

Upon browsing through npm highly regarded packages, I noticed that popular projects such as Grunt, lodash, and underscore are readily available. I have always utilized these in the traditional manner: <script src="js/lib/lodash.min.js"></script& ...

The action method does not get triggered when using $.ajax POST if the text being sent includes the character "<"

On my company's intranet site, I am facing an issue with displaying and submitting text. Here is the code snippet that I am using: @Html.TextAreaFor(model => model.Text) The problem arises when the text in the textarea contains XML-like formattin ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

I am having trouble unzipping the file

I encountered an issue while attempting to download a .zip file from Discord and extracting it using the decompress package. Despite not returning any errors, the package did not get extracted as expected. (The file was saved and downloaded correctly) co ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

Truncating long text labels in Material UI Autocomplete using ReactJS

I am currently utilizing the material UI autocomplete feature and I have a specific requirement to trim the label when it is too lengthy. <Autocomplete id="combo-box-demo" options={top100Films} getOptionLabel={(option) =& ...

Display previous messages in React JS chat when scrolling upwards

I am currently working on a chat application, as depicted in the image. Once the chat is initiated, it automatically scrolls down to display the most recent messages. My goal is to implement a feature where when a user scrolls up to reach the oldest mess ...

Is it permissible to use multiple JWT tokens in the HTTP header?

Currently, I have implemented the jwt access and refresh token pattern for client-server communication. The method involves sending two jwt tokens in the header: the access token and the refresh token. This is done by adding the following code to the heade ...

Locate a specific item in an array using AngularJs based on a key and present its value on the View

Imagine you have an array of objects: $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}]; And a variable that corresponds to key. For instance: $scope.a = 3; In the Controller, you want ...

The usage of an import statement is not permissible outside of a module

Having some trouble using the mathjs library to calculate complex solutions for the quadratic equation. No matter how I try to import the library into my code, I keep encountering errors. Initially, I attempted this method: At the top of my root.js file, ...

Troubleshooting Vue.js data binding problems

Utilizing HTML targeting with data binding <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div class="row" v-for="test in tests"> <div class="col-12"> <router-link tag="a" :to="{ name: ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...