【问题标题】:How to get results from MySql DB using node.js MySQL and send them back to API.ai - DialogFlow如何使用 node.js MySQL 从 MySql DB 获取结果并将它们发送回 API.ai - DialogFlow
【发布时间】:2018-02-06 13:37:33
【问题描述】:

我在从 MySql 数据库检索结果并将结果发送到 API.ai 时遇到问题。具体问题是如何等待结果可用,然后将Json对象中的结果发送回API.ai

这就是我所拥有的:

在webhook或者service中,我收到Json请求后,调用一个方法:

if (action === 'get.data') {
    // Call the callDBJokes method
    callDB().then((output) => {
        // Return the results to API.AI
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(output));
    }).catch((error) => {
        // If there is an error let the user know
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(error));
    });

}

调用执行数据库调用的方法callDB():

function callDB() {
return new Promise((resolve, reject) => {

    try {

        var connection = mysql.createConnection({
            host: "127.0.0.1",
            user: "root",
            password: "x",
            database: 'y'
        });

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (!error) {

                let response = "The solution is: " + results[0].solution;
                response = response.toString();
                let output = {'speech': response, 'displayText': response};
                console.log(output);
                resolve(output);

            } else {

                let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
                console.log(output);
                reject(output);

            }
        });
        connection.end();

    } catch (err) {
        let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
        console.log(output);
        reject(output);

    }

}
);

}

我在 API.ai 中得到一个 Json 响应,例如:

{
  "id": "5daf182b-009f-4c11-a654-f2c65caa415e",
  "timestamp": "2017-08-29T07:24:39.709Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "get data",
    "action": "get.data",
    "actionIncomplete": false,
    "parameters": {},
    "contexts": [
      {
        "name": "location",
        "parameters": {
          "date": "",
          "geo-city": "Perth",
          "date.original": "",
          "geo-city.original": "perth"
        },
        "lifespan": 2
      },
      {
        "name": "smalltalkagentgeneral-followup",
        "parameters": {},
        "lifespan": 2
      }
    ],
    "metadata": {
      "intentId": "4043ad70-289f-441c-9381-e82fdd9a9985",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "webhookResponseTime": 387,
      "intentName": "smalltalk.agent.general"
    },
    **"fulfillment": {
      "speech": "error",
      "displayText": "error",
      "messages": [
        {
          "type": 0,
          "speech": "error"**
        }
      ]
    },
    "score": 1
  },
  **"status": {
    "code": 200,
    "errorType": "success"**
  },
  "sessionId": "c326c828-aa47-490c-9ca0-37827a4e348a"
}

我只收到错误消息,但没有收到来自数据库的结果。我读到它也可以使用回调来完成,但我还想不通。我可以看到数据库连接正在工作,因为连接日志显示了连接尝试。

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 使用console.log() 调试您的代码。另外我推荐 if(!error) 的 else 部分,你可以在其中执行 reject(error);检查连接是否正常。
  • 您在访问数据库时似乎出错了。我将隔离并尝试仅运行访问您的数据库的代码,查看您遇到的错误并修复错误并从那里进行迭代。然后将固定的数据库访问代码放回您的应用程序中,然后重试。
  • 您是否在您的机器上正确设置了 MySQL 数据库?
  • @Myonara,感谢您的评论。我通常使用console.log() 进行调试,只是将其删除以减少示例的扩展。添加了console.log() 加上其他。在我将var mysql = require('mysql'); 移动到文件顶部,在exports.[myfunction]() 声明之前,代码可以正常工作,并像const mysql = require('mysql'); 一样离开它。
  • @matthewayne,我隔离了代码,发现我必须将var mysql = require('mysql'); 声明为const mysql = require('mysql');,而不是在函数内部,而是在exports.[myfunction]() 声明之前。现在它正在工作。谢谢。

标签: mysql json node.js dialogflow-es


【解决方案1】:

通过声明 var mysql = require('mysql'); 解决as const mysql = require('mysql');不在函数内部,而是在exports.myfunction 声明之前。使用 node.js MySQL 从 MySql DB 获取结果并将其发送回 API.ai 的工作示例代码如下:

    'use strict';
    const mysql = require('mysql');

    exports.her_goes_your_function_name = (req, res) => { //add your function name
        //Determine the required action
        let action = req.body.result['action'];

    if (action === 'get.data') {

        // Call the callDBJokes method
        callDB().then((output) => {
            // Return the results of the weather API to API.AI
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify(output));
        }).catch((error) => {
            // If there is an error let the user know
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify(error));
        });

    }
    };

    function callDB() {
        return new Promise((resolve, reject) => {

        try {

            var connection = mysql.createConnection({
                host: "127.0.0.1",
                user: "your_user",
                password: "your_pass",
                database: "your_DB"
            });

            connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
                if (!error) {

                    let response = "The solution is: " + results[0].solution;
                    response = response.toString();
                    let output = {'speech': response, 'displayText': response};
                    console.log(output);
                    resolve(output);

                } else {

                    let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
                    console.log(output);
                    reject(output);

                }
            });
            connection.end();

        } catch (err) {
            let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
            console.log(output);
            reject(output);

        }

    }
    );
}

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多