Passport JS “Can't set headers after they are sent”

99封情书 提交于 2019-12-08 15:29:17

问题


Getting this error when I successfully log in with passport JS. Trying to redirect to the home page once I log in.

Code that does it:

app.post('/login', 
  passport.authenticate('local', {failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Full Error:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:644:11)

Am I missing something? Not sure why this error is happening. I'm still able to use the app, I just dont want the error.


回答1:


You are redirecting the user so serializeUser function is being called twice. And in

 passport.use(new FacebookStrategy({
 ...

be sure to add this else or it gets called twice, thus sending the headers twice and causing error. Try this:

passport.use(new FacebookStrategy({
...
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {

  // To keep the example simple, the user's Facebook profile is returned to
  // represent the logged-in user.  In a typical application, you would want
  // to associate the Facebook account with a user record in your database,
  // and return that user instead.
    User.findByFacebookId({facebookId: profile.id}, function(err, user) {
        if (err) { return done(err); }
        if (!user) {
            //create user User.create...
            return done(null, createdUser);
        } else { //add this else
            return done(null, user);
        }
    });
  });
 }
));



回答2:


According to the PassportJS guide, you're supposed to let their middleware do all of the redirects.

app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                failureRedirect: '/login' }));

My guess is that the middleware is calling Express' res.redirect method just like you are in your example above, but has an error in its implementation (calling next when it shouldn't) and then your method is trying to call res.redirect again, and that causes the error to be thrown because you can only send a response to the client once in the HTTP protocol.



来源:https://stackoverflow.com/questions/13557256/passport-js-cant-set-headers-after-they-are-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!