2016-10-18 74 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); 
});