G
G
gomerIT2021-01-09 16:03:15
Express.js
gomerIT, 2021-01-09 16:03:15

How to avoid Cannot set headers after they are sent to the client error?

router.get('/', async (req, res, next) => {
  const token = req.query.token;
  if (!token) {
    res.json({
      status: 'error',
      message: 'Не передан токен авторизации',
    });
  }

  res.json({
    status: 'ok',
    message: `Токен: ${token}`,
  });
});

I assume this is due to two res.json, but why does this happen if only one condition is met, what to do? If I have 3 or more conditions and I need to send my own json response for each, what should I do in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2021-01-09
@SagePtr

After sending the response, exit the function with return, do not continue executing it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question