护照JS“发送后无法设置标题”

当我用护照JS成功login时得到这个错误。 尝试重新定向到主页,一旦我login。

这样做的代码:

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) 

我错过了什么吗? 不知道为什么这个错误发生。 我仍然能够使用该应用程序,我只是不想要的错误。

你正在redirect用户,所以serializeUser函数被调用两次。 而且,

  passport.use(new FacebookStrategy({ ... 

一定要添加这个否则它被调用两次,从而发送两次头,导致错误。 尝试这个:

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

根据PassportJS指南 ,你应该让他们的中间件做所有的redirect。

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

我的猜测是,中间件正在调用res.redirect方法,就像你在上面的例子中一样,但是在它的实现中有一个错误(当它不应该调用时),然后你的方法试图调用res.redirect再次,这会导致错误被抛出,因为你只能在HTTP协议中发送一次响应给客户端。