我已经看到了一些答案,但对于如何在Google助手上调用REST API for Actions仍然有些困惑。
这是我的代码:
'use strict';
// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');
const http = require('https');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
// Handle the Dialogflow intent named 'favorite color'.
// The intent collects a parameter named 'color'.
app.intent('favorite color', (conv, {any}) => {
//const luckyNumber = any.length;
// Respond with the user's lucky number and end the conversation.
//conv.close('Your lucky number is ' + luckyNumber);
return callApi(any).then((output) => {
console.log(output);
conv.close(`I found ${output.length} items!!`);
}).catch(() => {
conv.close('Error occurred while trying to get vehicles. Please try again later.');
});
});
function callApi (any){
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the vehicle
//Make the HTTP request to get the vehicle
http.get({host: 'hawking.sv.cmu.edu', port: 9023, path: '/dataset/temporary'}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
let output = {};
//
// //copy required response attributes to output here
//
console.log(response.length.toString());
resolve(output);
// callback(output);
});
res.on('error', (error) => {
console.log(`Error calling the API: ${error}`)
reject();
});
}); //http.get
// let output = {};
// resolve(output);
}); //promise
}
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
它总是表明:
格式错误的响应 必须设置“ final_response”。
http.get似乎是异步的,并且在发出http请求之前,它已经返回了结果,而无需等待完成请求。
我已经在app.intent函数中添加了“ return”,但仍然无法正常工作。
有什么建议吗?
谢谢!
答案 0 :(得分:-1)
app.intent('demo14mata', (conv, {any}) => {
var html = ""
http.get(url,(res)=>{
res.on("data",(data)=>{
html+=data
})
res.on("end",()=>{
console.log(html)
conv.close('return info is' + html);
})
}).on("error",(e)=>{
console.log('something wrong')
conv.close('no info return');
})
conv.close('no info return is(outside)' + html);
});