2016-10-18 138 views
0

「Express:它們發送後無法設置標頭」我是Express和Node的新手,並且在使用高級REST客戶端測試應用程序中受保護的REST端點時,數據從端點返回到客戶如預期,但控制檯日誌快速應用程序與節點

"Error: Can't set headers after they are sent" 

它停止服務器。這裏SO搜索,這似乎發送多個響應時發生,但我不明白,在我的代碼:

router.get('/books', userAuthenticated, function (req, res, next) { 
    Book.find({}, function(err, docs){ 
     if(err) { 
      res.send(err) 
     } else { 
      res.send(docs); 
      // next(); 
      // return; 
     } 
    }) 
}); 

這個錯誤是從客戶端發送一個請求/響應時/或預計上午我錯過了處理服務器上的錯誤的東西?

+0

最佳猜測是userAuthenticated中間件發送響應。檢查該函數,確保res在調用next()之前不會被髮送() – Brian

+0

這裏是我已經重構的userAuthenticated中間件,儘管我儘可以簡單,但仍然是相同的錯誤:function userAuthenticated(req,res,next){if isAuthenticated())return next(); } res.redirect('/ notloggedin'); } – user2232681

+0

檢查您的瀏覽器或郵遞員的回覆。打開開發控制檯,進入網絡,然後檢查請求/書籍 – Brian

回答

0

Express是一個node.js服務器,它具有一個名爲「中間件」的概念,其中多層代碼有機會對請求進行操作。

在這種情況下,您不僅需要檢查您的函數是否不發送兩次響應,而且還必須檢查其他中間件是否還沒有發回響應。

對於您的情況,代碼表示在此函數之前正在調用名爲「userAuthenticated」的中間件。您應該檢查該中間件是否已經發送響應。

+0

這裏是userAuthenticated中間件,我重構了儘可能簡單但仍然相同的錯誤:function userAuthenticated(req,res,next){if(req.isAuthenticated()){return next(); } res.redirect('/ notloggedin'); } – user2232681

0
I don't think the problem was in the middleware. It looks like I was calling done() twice in passport deserialize. I commented out the first instance and the problem disappeared in all my routes. Although, I am not sure if I should comment out the first or second instance but I'll work on that next. 
passport.deserializeUser(function(obj, done) { 
    console.log(obj); 
    Account.findById(obj, function(err, user) { 
     console.log(user); 
     //done(err, user); 
    }); 
return done(null, obj); 
});