2012-11-26 64 views
9

當我成功使用護照JS登錄時,發生此錯誤。嘗試一次我登錄,做它護照JS「發送後無法設置標題」

代碼重定向到主頁:

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) 

我缺少的東西?不知道爲什麼這個錯誤發生。我仍然能夠使用該應用程序,我只是不想錯誤。

回答

15

您正在重定向用戶,所以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); 
     } 
    }); 
    }); 
} 
)); 
+4

謝謝,我打電話完成()兩次 – wesbos

+2

感謝你。在意識到你需要'其他'之前,我做了很多頭部劃傷。順便說一句好用戶名和頭像。 – electrichead

1

根據PassportJS guide,你應該讓他們的中間件做所有的重定向。

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

我的猜測是,中間件調用快車res.redirect方法就像你在你上面的例子,但在其實施有錯誤(調用next當它不應該),然後你的方法試圖再次調用res.redirect,並且導致錯誤被拋出,因爲您只能在HTTP協議中向客戶端發送一次響應。

相關問題