pmiranda
pmiranda

Reputation: 8420

Nodejs, restify, res.send() Cannot set headers after they are sent

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.

Upvotes: 0

Views: 208

Answers (2)

Francisco Solar
Francisco Solar

Reputation: 41

So this happens because the execution reach the line

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

It sends the response, how its supposed to, but then the code continue its execution since there's 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 already 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 before 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');

Upvotes: 1

ardritkrasniqi
ardritkrasniqi

Reputation: 839

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().

Upvotes: 0

Related Questions