首页 > 解决方案 > 必须设置使用 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);

得到结果后,我会解析并使用它。

以下是我从堆栈溢出解决方案中尝试的参考点:

感谢社区的任何帮助。

标签: node.jsgoogle-cloud-functionsactions-on-googledialogflow-es

解决方案


在大多数涉及 MalformedResponse 和使用类似的异步调用的情况下request,问题是您在回调之外发送响应。这通常是因为库期待一个 Promise,而您正在以非 Promise 的方式处理事情。

我通常的做法是:

所以(非常粗略)

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?` );
  });

推荐阅读