Making an HTTP POST request from fulfillment in Dialogflow

后端 未结 1 1480
忘了有多久
忘了有多久 2020-12-11 21:28

I am writing a handler for an intent to generate a PDF. This API accepts a POST request with the JSON data and returns a link to the generated PDF. The intent triggers this

相关标签:
1条回答
  • 2020-12-11 22:02

    If you are doing async calls, your handler function needs to return a Promise. Otherwise the handler dispatcher doesn't know there is an async call and will end immediately after the function returns.

    The easiest way to use promises with network calls is to use a package such as request-promise-native. Using this, your code might look something like:

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

    If you really wanted to keep using xhr, you need to wrap it in a Promise. Possibly something like

    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();
        }
      };
    
    });
    
    0 讨论(0)
提交回复
热议问题