Passport JS"无法在发送后设置标头"

wes*_*bos 11 javascript node.js express passport.js

使用护照JS成功登录时出现此错误.登录后尝试重定向到主页.

执行它的代码:

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

完全错误:

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

我错过了什么吗?不确定为什么会发生这种错误.我仍然可以使用该应用程序,我只是不想要错误.

1.4*_*4mb 18

您正在重定向用户,因此serializeUser函数被调用两次.并在

 passport.use(new FacebookStrategy({
 ...
Run Code Online (Sandbox Code Playgroud)

一定要添加其他,否则会被调用两次,从而发送两次标题并导致错误.试试这个:

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);
        }
    });
  });
 }
));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你.在意识到你需要'其他'之前,我做了很多事.顺便说一句好的用户名和头像. (3认同)