1

I am new to node and async...

I am getting an error saying I can't set headers after they sent when I am sending a response back to api-ai

Any idea why?

Below is the code for function - getUserFirstName(userId, name, callback):

var name = "";
function getUserFirstName(userId, name, callback) {
  console.log('withParams function called');

  request({
      method: 'GET',
      uri: "https://graph.facebook.com/v2.6/" + userId + "?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=" + FB_PAGE_ACCESS_TOKEN
  },
  function (error, response) {
    if (error) {
        console.error('Error while userInfoRequest: ', error);
    } else {
        if(!typeof response.body != 'object'){
          var body = JSON.parse(response.body);
          name = body.first_name;
          callback(null,name);
        }else{
          name = response.body.first_name;
          callback(null,name);
        }
    }
  });
}

Here is the code being executed:

app.post('/webhook/', (req, res) => {
      var data = JSONbig.parse(req.body);        
      var action = data.result.action;
      var facebook_message = [];

      if(action == "input.welcome"){
        var userId = data.originalRequest.data.sender.id;

        async.series([
          function(callback) {
            getUserFirstName(userId, name, callback);
          }
        ], function(err,results) {

          if (results != undefined){ // results = "John" 

            facebook_message = [{
              "text":"Heyyyoo. Welcome!"
            }]
          }else{
            facebook_message = [{
              "text":"Hey " + results +"! Welcome!" // Hey John! Welcome!
            }]
          }

          res.json({ // line 308 - error here!
            speech: "Greetings",
            displayText: "Greetings",
            "data": {
              "facebook": facebook_message
            },
            source: "webhook"
          });
        });

      }

      // BUNCH OF LONG AND MESSY CODES OVER HERE...

      return res.status(200).json({
        status: "ok"
      });

Error

Error: Cant set headers after they are sent.
   at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
   at ServerResponse.header (/app/node_modules/express/lib/response.js:719:10)
   at ServerResponse.send (/app/mode_modules/express/lib/response.js:164:12)
   at ServerRespose.json (/app/mode_modules/express/lib/response.js:250:15)
   at /app/src/app.js: 308:15
   at /app/node_modules/async/dist/async.js:3694:9
   at /app/node_modules/async/dist/async.js:356:16
   at replenish (/app/node_modules/async/dist/async.js:877.25)
   at iterateeCallback (/app/node_modules/async/dist/async.js:867:17)
   at /app/node_modules/async/dist/async.js:840:16
  • Why would you use `async.series()` for one async operation. That makes no sense. – jfriend00 Feb 05 '17 at 05:38
  • Where exactly is this error coming from? I don't see an obvious reason for that error in the code you show. – jfriend00 Feb 05 '17 at 06:05
  • I think you should reproduce your error message as it is, here. – Ritik Saxena Feb 05 '17 at 06:12
  • @jfriend00 - Hey. Really sorry for not hanging around. Was taking a break just now. I will be using more than one async operation in the future. I will post the error message shortly. – Harrizontal Feb 05 '17 at 07:05
  • @RitikSaxena Hey guys, just added the error message. There is an error on my **res.json** – Harrizontal Feb 05 '17 at 07:23
  • @Harrizontal one thing which might be the reason is that the `request` in your `getUserFirstName` is asynchronous. try this - add a `console.log("some unique value")` inside `function(err,results)`, outside `async.series`, and inside `else` part of your `request` 's callback (`function(error,response)`) inside `getUserFirstName`, and analyze the flow of execution. It might be an error due to asynchronous nature of `request`. – Ritik Saxena Feb 05 '17 at 07:39
  • Is there more to your `app.post('/webhook/'` handler than you are showing us? Based on the error and the code, I'm guessing there's more to it that you aren't showing us and that other part of the code is what is causing the error. – jfriend00 Feb 05 '17 at 09:47
  • @jfriend00 Hey, thank you for enlightening me. I found the cause of the error. Apparently, I am sending another `res.json()` at the end of my code and it's clashing with my initial response. I removed and it worked! – Harrizontal Feb 05 '17 at 12:41

1 Answers1

1

Remove the following:

return res.status(200).json({
      status: "ok"
});