0

I am new to Express and Node, and when testing a protected REST endpoint in my app using Advanced REST Client the data is returned from the endpoint to the Client as expected, however the console logs

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

which stops the server. Searching here on SO, this seems to occur when sending more than one response but I don't see that in my code:

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

Is this error expected when sending a request/response to/from the Client or am I missing something in handling the error on the server?

QoP
  • 27,388
  • 16
  • 74
  • 74
user2232681
  • 839
  • 4
  • 16
  • 33
  • best guess would be userAuthenticated middleware sends a response. check that function, make sure res is not sent before calling next() – Brian Oct 18 '16 at 02:29
  • Here's the userAuthenticated middleware which I have refactored as simply as I can but still the same error: function userAuthenticated(req, res, next){ if(req.isAuthenticated()){ return next(); } res.redirect('/notloggedin'); } – user2232681 Oct 18 '16 at 02:46
  • check the response on your browser, or postman. open the dev console, go to networking, then check the request for /books – Brian Oct 18 '16 at 10:50
  • Also, check other mounted middlewares that apply to the path. eg: app.use('/books', fn..); – Brian Oct 18 '16 at 11:06

2 Answers2

0

Express is a node.js server that features a concept called "middleware", where multiple layers of code get a chance to operate on a request.

In that case, not only do you need to check that your function is not sending back a response twice, but you have to check that other middleware are not sending back a response as well.

In your case, the code indicates that middleware called "userAuthenticated" is being invoked before this function. You should check if that middleware is already sending a response.

  • Here's the userAuthenticated middleware which I have refactored as simply as I can but still the same error: function userAuthenticated(req, res, next){ if(req.isAuthenticated()){ return next(); } res.redirect('/notloggedin'); } – user2232681 Oct 18 '16 at 02:49
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);
});
user2232681
  • 839
  • 4
  • 16
  • 33