2017-08-29 18 views
1

我遇到问题,从MySql数据库检索结果并将结果发送到API.ai.具体问题是如何等待结果可用,然后在JSON对象将结果发送回API.ai如何使用node.js MySQL从MySql DB获取结果并将它们发送回API.ai - DialogFlow

这是我有:

在网络挂接或服务,接收后的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" 
} 

我只得到了错误消息,但不会从数据库中的结果。我读过它也可以使用回调来完成,但我还没弄明白。我可以看到数据库连接正在工作,因为连接的日志显示连接尝试。

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

+1

使用'的console.log()'调试代码。我还推荐if(!error)的其他部分,您可以在其中进行拒绝(错误);检查连接是否正常工作。 – Myonara

+1

好像你在访问数据库时出错。我将隔离并尝试运行访问数据库的代码,查看出现的错误并修复出现的问题并从中进行迭代。然后将固定的数据库访问代码放回到您的应用程序中,然后重试。 – matthewayne

+0

您是否正确地在您的机器上设置了您的MySQL数据库? – matthewayne

回答

1

通过声明var mysql = require('mysql'); as const mysql = require('mysql');不在函数内部,而是在exports.myfunction声明之前。工作示例代码以获取如何使用Node.js的MySQL从MySQL数据库的结果,并且将它们送回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); 

     } 

    } 
    ); 
} 
相关问题