@jedifa

Что делать если выходит ошибка Cannot set headers after they are sent to the client?

Вот мой код:

router.get('/course-cart/:id', async (req, res) => {
    try {
        const courseId = await req.params.id;
        const userId = await req.query[0];
        const user = await User.findById(userId);
        if (user) {
            await user.courses.map(item => {
                const has = item._id;
                try {
          
                    if (has !== courseId) return res.end();

                    return res.json('Курс уже приобретен!').end();
                } catch(e) {
                    return console.log(e);
                }
            });
        } else {
            return res.status(400).json('Нужно войти!')
        }
    } catch (e) {
        console.log(e)
    }
});


Далее выходит ошибка:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at ServerResponse.setHeader (_http_outgoing.js:561:11)
[0]     at ServerResponse.header (/Users/user/Desktop/path/path/node_modules/express/lib/response.js:771:10)
[0]     at ServerResponse.json (/Users/user/Desktop/path/path/node_modules/express/lib/response.js:264:10)
[0]     at /Users/user/Desktop/path/path/routes/courses.route.js:75:32
[0]     at CoreMongooseArray.map (<anonymous>)
[0]     at /Users/user/Desktop/path/path/routes/courses.route.js:65:32
[0]     at processTicksAndRejections (internal/process/task_queues.js:95:5) {
[0]   code: 'ERR_HTTP_HEADERS_SENT'
[0] }


Уже гуглил в основном писали что проблема решается добавлением return но как видите return добавил практически везде где только возможно
  • Вопрос задан
  • 273 просмотра
Пригласить эксперта
Ответы на вопрос 1
@Azizbek1
У меня таже проблема!
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы