异步 - 发送后无法设置标头

时间:2017-02-05 05:32:51

标签: javascript express asynchronous response api-ai

我是节点和异步的新手......

我收到错误消息说我在发送后我将回复发送回api-ai时无法设置标题

知道为什么吗?

下面是函数的代码 - 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);
        }
    }
  });
}

以下是正在执行的代码:

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: 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

1 个答案:

答案 0 :(得分:1)

删除以下内容:

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