Home > Back-end >  Cannot set headers after they are sent to the client. NOT USING TWO RESPONSES
Cannot set headers after they are sent to the client. NOT USING TWO RESPONSES

Time:11-05

JUST WANTED TO ASK

i have this function that is called from the router

this is middleware that is executed before the previous function

after hitting the entry-point i had this error message

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:174:12)
    at ServerResponse.json (C:\Users\mmeeee\Desktop\REACT_APP\node_modules\express\lib\response.js:278:15)
    at C:\Users\mmeeee\Desktop\REACT_APP\backend\controllers\userController.js:27:9
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

i tried to replace res.json with res.end but it seems not to be the problem right here.

CodePudding user response:

In that protected middleware, you are invoking next, which could have the side effect of sending the response to the client, in the try block. You are also sending the response to the client in the catch block. After either of those blocks have executed, you should not try to modify the response further, which you do if you end up without a token. A potential refactoring:

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      const token = req.headers.authorization.split(" ")[1];
      if (!token) throw 'No token!'
      const decoded = theCodeYouWrote(token);
      req.user = await theCodeYouWroteForTheUser(decoded);
    } catch (error) {
      console.error(error);
      res.status(401).json(...);
      return;
    }
  }
  next();
  • Related