简体   繁体   中英

Get json body through function callback for api.ai

I am using firebase for hosting cloud functions, since many functions (about every) I need to make the http request and get the json body to get the data from it. However, the callback doesn't work quite well for me, I've searched some existing answers but still get stuck on this. Here is the code snippet, options are declared before and if I do not put the request within get_request_handler it works fine.:

function get_request_handler(assistant, input_url, callback) {
  req(options, function (error, response, body) {
     if (!error && response.statusCode == 200) {
      var cookie = req.cookie('BPMSTS=' + body );
      var headers = {
          'Content-Type': 'application/json',
          'Cookie': cookie
      };
      var option = {
          url: input_url,
          method: 'GET',
          headers: headers
      }
      req(option, function(error, res, body) {
          assistant.ask(input_url);
          if (!error && res.statusCode == 200) {
              callback(JSON.parse(body));
          } else {
              assistant.ask('inner request with error code: ' + (res.statusCode).toString());
          }
      });
     } else {
      assistant.ask('outer request with error code: ' + (response.statusCode).toString());
    }
  });
}

I call the function as follows:

get_request_handler(assistant, workflow_url, function(cur_json){assistant.ask(cur_json);});

The problem right now is the first request can't be made in the get_request_handler function. In other words, it only goes in to get_request_handler but not go into that request body. If I do not create get_request_handler and left req(options, function (error, response, body) { ... } it works without any problem. Any ideas on this?

Note: I just checked firebase log and it says for this line: req(options, function (error, response, body) it got TypeError: Assignment to constant variable. at get_request_handler (/user_code/index.js:116:13)

You have a lot of problems here, but the basic one is that you're trying to call assistant.ask() more than once in your response to the user. Once you call assistant.ask() , no further responses can be sent, and none of the other calls to ask() will be handled.

It looks like you're using it for debugging. That seems a really poor choice when you should be using console.log() .

You also indicated that you're using Firebase Functions. Note that calls out from a Firebase function are restricted if you're on the free plan. If you're on one of the paid plans there is no restriction, and there is a free tier which should be more than sufficient for testing.

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