node.jsexpressadvanced-rest-client

"Error: Can't set headers after they are sent" in Express app with Node


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?


Solution

  • 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.