简体   繁体   中英

how to make post request in inline editor dialogflow?

First of all,I am using the blaze tier, so no issue of billing. I have also included
"request" : "*"
in package.json dependencies. Look at my code index.js in the inline editor:

`

'use strict';
var global_request = require('request');
var myJSONObject = {
        "limit": 10,
        "offset": 0,
        "query": "example"
    };
global_request.post(
    'https://example.com', { 
        json: myJSONObject },
        function (error, res, body) {
            if (!error && res.statusCode == 200) {
                console.log(res);
                console.log(body);
            }
        }
    );

`

But in the firebase log I am getting the following error:

Unhandled rejection
Error: Can't set headers after they are sent.

I followed How to make an HTTP POST request in node.js? for help. But the code still has errors. What am I doing wrong here?? Thanks for help.

The Dialogflow library assumes that you're using Promises if you're doing asynchronous operations.

Typically, instead of using the request library, I use the request-promise-native library. So that block of code might look something like this:

var rp = require('request-promise-native');
var myJSONObject = {
        "limit": 10,
        "offset": 0,
        "query": "example"
    };
var options = {
  method: 'post',
  uri: 'https://example.com',
  body: myJSONObject,
  json: true
};
return rp( options )
  .then( body => {
    console.log( body );
    // This is also where you'd call the library
    // to send a reply.
    return Promise.resolve( true );
  })
  .catch( err => {
    // You should also return a message here of some sort
    return Promise.resolve( true );
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM