【问题标题】:Making an HTTP POST request from fulfillment in Dialogflow在 Dialogflow 中通过实现发出 HTTP POST 请求
【发布时间】:2019-03-04 10:23:04
【问题描述】:

我正在为生成 PDF 的意图编写处理程序。此 API 接受带有 JSON 数据的 POST 请求,并返回指向生成的 PDF 的链接。意图会触发此代码,但不会将答案添加到代理中。请求是否有可能没有转发到目的地? API 似乎没有收到任何请求。知道如何解决这个问题吗?

function fillDocument(agent) {
    const name = agent.parameters.name;
    const address = agent.parameters.newaddress;
    const doctype = agent.parameters.doctype;

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    var url = "https://us1.pdfgeneratorapi.com/api/v3/templates/36628/output?format=pdf&output=url";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("X-Auth-Key", "...");
    xhr.setRequestHeader("X-Auth-Secret", "...");
    xhr.setRequestHeader("X-Auth-Workspace", "...");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            agent.add(json.response);
        }
    };
    var data = JSON.stringify({...});
    xhr.send(data);
}

编辑:我开始在 GCP 中设置一个结算帐户,现在通话正常,但它是异步的。如果我通过这样做将其更改为 syn:

xhr.open("POST", url, false);

我收到以下错误:

EROFS: read-only file system, open '.node-xmlhttprequest-sync-2'

我需要它是异步的,因为我的机器人应该发送的响应取决于 API 的响应。关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: dialogflow-es


    【解决方案1】:

    如果你在做异步调用,你的处理函数需要返回一个 Promise。否则,handler dispatcher 不知道有异步调用,并且会在函数返回后立即结束。

    在网络调用中使用 Promise 的最简单方法是使用诸如 request-promise-native 之类的包。使用它,您的代码可能类似于:

    var options = {
      uri: url,
      method: 'POST',
      json: true,
      headers: { ... }
    };
    return rp(options)
      .then( body => {
        var val = body.someParameter;
        var msg = `The value is ${val}`;
        agent.add( msg );
      });
    

    如果你真的想继续使用 xhr,你需要将它包装在一个 Promise 中。可能是这样的

    return new Promise( (resolve,reject) => {
    
      var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
      // ... other XMLHttpRequest setup here
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var json = JSON.parse(xhr.responseText);
          agent.add(json.response);
          resolve();
        }
      };
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2017-05-17
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多