node.js - 必须设置使用 web-fulfillment 和 firebase 抛出 MalformedResponse 'final_response' 的操作
问题描述
环境:使用 Firebase 云部署的谷歌操作。Action 使用 webhook 从函数中获取结果。我正在使用 Blaze 计划,因此调用外部 URL 应该是合法的。我正在使用对话流 V2。
我的函数的部分工作是执行以下操作:我使用以下内容(屏蔽代码详细信息)发出外部 API 请求:
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);
得到结果后,我会解析并使用它。
以下是我从堆栈溢出解决方案中尝试的参考点:
感谢社区的任何帮助。
解决方案
在大多数涉及 MalformedResponse 和使用类似的异步调用的情况下request
,问题是您在回调之外发送响应。这通常是因为库期待一个 Promise,而您正在以非 Promise 的方式处理事情。
我通常的做法是:
- 使用request-promise库(或request-promise-native库)
- 在您获得结果的部分之一中
then
,请确保您致电conv.ask()
- 确保您返回承诺本身。
所以(非常粗略)
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?` );
});
推荐阅读
- kubernetes - Kubernetes - 将数据写入 StatefulSet 卷
- objective-c - 具有可编辑内容的 NSTreeController
- php - get_post_meta 在 WP_Query 循环中不起作用(返回空数组)
- reactjs - 在路线上重新渲染 Ionic React(不想重新加载数据)
- android - 当应用程序在后台时,为什么这个线程会继续运行?
- telegram-bot - 我需要在我的 PHP 文件中做什么,以便我的 Telegram 机器人在报价中回复我的消息?
- laravel - 如何使用 Laravel DB::table()->insert() 获取最后插入的行?
- variables - 如何从 shell 命令的输出中分配 Makefile 变量
- ios - callback_cache.cc(132) 无法解析回调缓存,中止恢复 - [Flutter]
- c# - Java/Spring boot/Spring Data 中实体框架中的 DataContext 类的等价物