npmnode.js95% confidence\u2191 138

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

Full error message
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!

That particular error occurs whenever your code attempts to send more than one response to the same request. There are a number of different coding mistakes that can lead to this: Improperly written asynchronous code that allows multiple branches to send a response. Not returning from the request handler to stop further code in the request handler from running after you've sent a response. Calling next() when you've already sent a response. Improper logic branching that allows multiple code paths to execute and attempt to send a response. 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 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 other words, 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. Or, you can send to centralized Express error handling: if (err) { console.log(err); next(err); return; } And, then you can catch all of these in an Express error handler. 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.

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/39e175884bc33dede9e7d610e41e1a4b5a67e6f0647733400c33e51307c31a5a
hash \u00b7 39e175884bc33dede9e7d610e41e1a4b5a67e6f0647733400c33e51307c31a5a
ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sen… — DepScope fix | DepScope