J
J
jedifa2021-07-02 17:30:17
Express.js
jedifa, 2021-07-02 17:30:17

What should I do if I get the error Cannot set headers after they are sent to the client?

Here is my code:

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)
    }
});


Following is the error:

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] }


Already googled, basically they wrote that the problem is solved by adding return, but as you can see, return was added almost everywhere where possible

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question