簡體   English   中英

使用 AXIOS 顯示來自 JSON 外部 API 的數據並顯示到 DIALOGFLOW

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

我需要幫助來顯示從我的 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 日志

我對result.data.map代碼行遇到了真正的麻煩。 最后,我避免了它,而是在result.data .then((result) => {行之后通過檢查我的 API 返回的數組長度來處理result.data ,如果它> 0 ,則循環遍歷它以單獨輸出每一行, 使用agent.add 。如果數組長度為 0,我使用agent.add顯示一條消息說“未找到記錄”。我使用catch來記錄任何錯誤(同樣,使用agent.add將錯誤消息發送到用戶)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM