Passport JS“发送后无法设置头" [英] Passport JS "Can't set headers after they are sent"

查看:57
本文介绍了Passport JS“发送后无法设置头"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

执行此操作的代码:

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

完全错误:

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.

推荐答案

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

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

 passport.use(new FacebookStrategy({
 ...

请确保添加此 else 否则它会被调用两次,从而两次发送标头并导致错误.试试这个:

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);
        }
    });
  });
 }
));

这篇关于Passport JS“发送后无法设置头"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆