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"
}
我只得到了錯誤消息,但不會從數據庫中的結果。我讀過它也可以使用回調來完成,但我還沒弄明白。我可以看到數據庫連接正在工作,因爲連接的日誌顯示連接嘗試。
任何幫助將不勝感激。謝謝。
使用'的console.log()'調試代碼。我還推薦if(!error)的其他部分,您可以在其中進行拒絕(錯誤);檢查連接是否正常工作。 – Myonara
好像你在訪問數據庫時出錯。我將隔離並嘗試運行訪問數據庫的代碼,查看出現的錯誤並修復出現的問題並從中進行迭代。然後將固定的數據庫訪問代碼放回到您的應用程序中,然後重試。 – matthewayne
您是否正確地在您的機器上設置了您的MySQL數據庫? – matthewayne