Env : Using firebase cloud deployed google action. Action is using webhook to get results from functions. I am using Blaze plan so calling external URL should be legit. I am using dialogflow V2.
Part of my function's job is doing the following: I make an external API request using the following (Masked code detail):
var requestObj = require('request');
var options = {
url: 'my url',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
result = JSON.parse(body).element;
console.log('Title 0 ' + result);
}
}
requestObj(options, callback);
Once I have the result, I parse it and use it.
Following are my reference points that I tried from stack overflow solutions:
Would appreciate any help from the community.
In most cases involving the MalformedResponse and an asynchronous call using something like request
, the problem is that you're sending the response outside of the callback. Frequently this is because the library is expecting a Promise and you are handling things in a non-promise like way.
My usual practice is:
- use the request-promise library (or the request-promise-native library)
- in one of the
then
sections where you get the results, make sure you callconv.ask()
- make sure you return the promise itself.
So (very roughly)
var request = require('request-promise-native');
var options = {
uri: 'https://example.com/api',
json: true // Automatically parses the JSON string in the response
};
return request(options)
.then( response => {
// The response will be a JSON object already. Do whatever with it.
var value = response.whatever.you.want;
return conv.ask( `The value is ${value}. What now?` );
});
来源:https://stackoverflow.com/questions/50361643/action-using-web-fulfillment-with-firebase-throwing-malformedresponse-final-res