0

我是 Express 和 Node 的新手,当使用 Advanced REST Client 在我的应用程序中测试受保护的 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;
       }
   })  
});

向/从客户端发送请求/响应时是否会出现此错误,或者我在处理服务器上的错误时遗漏了什么?

4

2 回答 2

0

Express 是一个 node.js 服务器,具有称为“中间件”的概念,其中多层代码有机会对请求进行操作。

在这种情况下,您不仅需要检查您的函数是否没有两次发回响应,还必须检查其他中间件是否也没有发回响应。

在您的情况下,代码表明在此函数之前调用了名为“userAuthenticated”的中间件。您应该检查该中间件是否已经在发送响应。

于 2016-10-18T02:31:33.123 回答
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);
});
于 2016-10-21T16:33:18.643 回答