节点&快速/错误:发送后无法设置标头

时间:2015-01-18 16:03:50

标签: node.js express

您好我有以下方法,我无法确定我收到此错误的原因

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.header (/projects/6degreeswithfriends/node/node_modules/express/lib/response.js:666:10)
at ServerResponse.send (/projects/6degreeswithfriends/node/node_modules/express/lib/response.js:146:12)
at /projects/6degreeswithfriends/node/app.js:92:10
at IncomingMessage.<anonymous> (/projects/6degreeswithfriends/node/User.js:68:13)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

我的方法如下:

 app.post('/facebook/friends',
  passport.authenticate('facebook-token'),
  function (req, res) {
    console.log("API:/facebook/friends: Profile id is " + req.user.id + " :accessToken is "+req.body.access_token);
    User.getFacebookFriends(req.body.access_token, req.user.profileId, function(data, err){

        console.log("User.getFacebookFriends#Callback#: " + data);
        if (err) {
            res.status(200);
            res.send({"error" : 100, "message": "Error retrieving friends"});
         } else {
            res.status(200);
            res.send(data);
        }
    });

  }
);

这似乎与在回调中的回调方法中调用res.send有关。这是一个问题吗?

如果我把res.send放在回调之外就行了。不确定为什么?

app.post('/facebook/friends',
  passport.authenticate('facebook-token'),
  function (req, res) {
    console.log("API:/facebook/friends: Profile id is " + req.user.id + " :accessToken is "+req.body.access_token);
    User.getFacebookFriends(req.body.access_token, req.user.profileId, function(data, err){

        console.log("User.getFacebookFriends#Callback#: " + data);
        // if (err) {
        //  res.status(200);
        //  res.send({"error" : 100, "message": "Error retrieving friends"});
        //  } else {
        //      res.status(200);
        //  res.send(data);
        // }
    });

    res.status(200);
    res.send(data);
  }
);

0 个答案:

没有答案