首页 > 解决方案 > 显示来自 JSON 外部 API 的数据并使用 AXIOS 显示到 DIALOGFLOW

问题描述

我需要有关显示从我的 API 获得的响应到 Dialogflow UI 的帮助。这是我的代码。我目前正在使用 WebHook 将 Dialogflow 连接到 Heroku 中的后端。 我的代码

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



当我 console.log 我的结果时。我在 console.log 输出中从 API 获取数据,但数据未显示在 Dialogflow UI 中,我也没有收到任何错误。

Heroku 日志

标签: node.jsaxiosdialogflow-eschatbotdialogflow-es-fulfillment

解决方案


我在代码行上遇到了真正的麻烦result.data.map。最后,我避免了它,而是通过检查我的 API 返回的数组长度在行result.data之后进行处理,如果是,则循环遍历它以单独输出每一行,使用. 如果数组长度为 0,我过去会显示一条消息“未找到记录”。我使用 a来记录任何错误(同样,使用向用户发送错误消息)。.then((result) => {> 0agent.addagent.addcatchagent.add


推荐阅读