Home > Software design >  Nodejs, restify, res.send() Cannot set headers after they are sent
Nodejs, restify, res.send() Cannot set headers after they are sent

Time:09-01

Each res.send(200, line when is reached according to the logic is working fine:

const implementation = async (req, res, next) => {
  try {
    if (req.rut) {
      const data = await someAPI();
      res.send(200, data); // WORKING
    } else {
      const data2 = await SomeAPI2();
      if (data2) {
        res.send(200, data2}); // WORKING
      }
      res.send(400, 'Error'); // ERROR
    }
  } catch (error) {
    res.send(400, error);
  }
};

but when the code reach the line that uses res.send(400 I'm getting this error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)

Why? I don't see that other res.send() lines are reached.

CodePudding user response:

So this happens beacouse the execution reach the line

      if (data2) {
        res.send(200, data2}); // WORKING
      }

It sends the response, how its suppoused to, but then the code continue its execution since theres nothing that tells it to stop (res.send() does not stop the execution) reaching the next line

      res.send(400, 'Error'); // ERROR

But because the response object was allready sent, it throws the error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)

An easy way to fix this is to add a return beafore each res.send, that will stop the execution, thus not reaching the next line of code, for example

if (data2) {
   return res.send(200, data2});
}
return res.send(400, 'Error');

CodePudding user response:

Even though i don't like the way you wrote the code this could solve your issue:

const implementation = async (req, res, next) => {
  try {
    if (req.rut) {
      const data = await someAPI();
      res.send(200, data); // WORKING
    } else {
      const data2 = await SomeAPI2();
      if (data2) {
        res.send(200, data2}); // WORKING
      } else {
         res.send(400, 'Error'); // ERROR
      }
    }
  } catch (error) {
    res.send(400, error);
  }
};

FYI:
i have added another else statement after you call the SomeAPI2().

  • Related