Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

I'm facing this weird issue in NodeJS when using with Passport.js, Express and Mongoose. Basically, I get an error saying "Cannot set headers after they are sent to the client" even though I don't send more than one header.

I've read other posts and tried them out as well, and none of them worked.

  • app.get - is there any difference between res.send vs return res.send
  • Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  • Cannot set headers after they are sent to the client

I've dug through github issues and I can't seem to find a solution. I get the problem that this error is triggered when I send multiple response headers, but the fact is that I am not sending multiple headers. It seems just weird.

This is my stack trace:

(node:9236) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Server Running on port 5000
MongoDB Connected Error
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  at validateHeader (_http_outgoing.js:503:11)
   at ServerResponse.setHeader (_http_outgoing.js:510:3)
   at ServerResponse.header (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:767:10)
   at ServerResponse.json (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:264:10)
   at Profile.findOne.then.profile (/Users/lourdesroashan/code/github/devlog/routes/api/profile.js:27:30)
   at <anonymous>

This is my server code:

router.get("/userprofile", passport.authenticate('jwt', { session: false }), (req, res) => {    Profile.findOne({ user: req.user.id }).then(profile => {     if (!profile) {       return res.status(404).json({ error: "No Profile Found" });     }     else {       res.json(profile);     }   }).catch(err => {     console.log(err);   }) }); 

I understand what the error means, but from what I know, I don't think I am sending multiple headers, I even checked by console.log that only one of the blocks is run.

Thank you so much in advance! :)

Full Code at: https://github.com/lourdesr/devlog

EDIT:

I figured it out. It was a problem in my passport.js while trying to get the authenticated user. I forgot to use 'return' on the 'done' method, which had caused it. Just added the return statement and it worked!

like image 487
lourdesr Avatar asked Aug 31 '18 20:08

lourdesr


People also ask

How do you fix Cannot set headers after they are sent to the client?

The "Cannot set headers after they are sent to the client" error occurs when the server in an express. js application sends more than one response for a single request, e.g. calling res. json() twice. To solve the error, make sure to only send a single response for each request.

What is middleware in node JS?

The middleware in node. js is a function that will have all the access for requesting an object, responding to an object, and moving to the next middleware function in the application request-response cycle.

What is RES end in node JS?

res. end() will end the response process. This method actually comes from Node core, specifically the response. end() method of http. ServerResponse .

Does Res send end the function?

send doesn't return the function, but does close the connection / end the request.


1 Answers

That particular error occurs whenever you try to send more than one response to the same request and is usually caused by improper asynchronous code.

The code you show in your question does not appear like it would cause that error, but I do see code in a different route here that would cause that error.

Where you have this:

if (!user) {   errors.email = "User not found";   res.status(404).json({ errors }); } 

You need to change it to:

if (!user) {   errors.email = "User not found";   res.status(404).json({ errors });   // stop further execution in this callback   return; } 

You don't want the code to continue after you've done res.status(404).json({ errors }); because it will then try to send another response.


In addition, everywhere you have this:

if (err) throw err; 

inside an async callback, you need to replace that with something that actually sends an error response such as:

if (err) {     console.log(err);     res.sendStatus(500);     return; } 

throwing inside an async callback just goes back into the node.js event system and isn't thrown to anywhere that you can actually catch it. Further, it doesn't send a response to the http request. In otherwords, it doesn't really do what the server is supposed to do. So, do yourself a favor and never write that code in your server. When you get an error, send an error response.


Since it looks like you may be new here, I wanted to compliment you on including a link to your full source code at https://github.com/lourdesr/devlog because it's only by looking at that that I was able to see this place where the error is occuring.

like image 58
jfriend00 Avatar answered Sep 17 '22 14:09

jfriend00