简体   繁体   中英

Display data from JSON external API and display to DIALOGFLOW using AXIOS

I need help with Displaying the response I get from my API to Dialogflow UI. Here is my code. I am currently using WebHook to connect Dialogflow to backend in Heroku. My code

const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("../../reactpageagent-dxug-firebase-adminsdk-26f6q-e1563ff30f.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://reactpageagent-dxug.firebaseio.com"
});

const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const axios = require('axios');

module.exports = (request, response) => {
  const agent = new WebhookClient({ request, response });

  function welcome(agent) {
    agent.add('Welcome to my agent');
  }

  function rhymingWordHandler(agent) {
    const word = agent.parameters.word;
    agent.add(`Here are the rhyming words for ${word}`)
    axios.get(`https://api.datamuse.com/words?rel_rhy=${word}`)
      .then((result) => {
        console.log(result.data);
        result.data.map(wordObj => {
          console.log(wordObj.word);
          agent.add(JSON.stringify(wordObj.word));
          return;
          // agent.end(`${wordObj.word}`);
        });
      });
  };

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('rhymingWord', rhymingWordHandler);
  agent.handleRequest(intentMap);
}



When I console.log my the result. I get the data from the API in my console.log output , but the Data is not displayed in Dialogflow UI I also do not get any error.

Heroku log

I had real trouble with the result.data.map line of code. In the end, I avoided it and instead processed result.data after the .then((result) => { line by checking the array length that my API returned, and if it was > 0 , loop through it to output each line individually, using agent.add . If the array length was 0, I used agent.add to display a message saying 'No records found'. I used a catch to log any errors (again, using agent.add to send an error message to the user).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM