@Nikita1244
Anonymous

Ошибка ERR_HTTP_HEADERS_SENT, что делать?

Здравствуйте. У меня возникает ошибка, которая уже написана в заголовке. Я знаю что она означает, но я не могу найти, что ее вызывает. Если ввести в поле неправильный код подтверждения, то сервер падает. Если ввести верный, то проходит дальше.
Логи

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:278:15)
    at /home/nikita/galaxy-of-hearing/index.js:183:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
node:internal/errors:477
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:278:15)
    at /home/nikita/galaxy-of-hearing/index.js:189:21
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}


Код

app.post('/email-verification', async (req, res) => {
    console.log(app.locals.code)
    if (req.body.code !== app.locals.code) {
        res.json({
            "status": "error",
            "error": "Неверный код подтверждения"
        });
    }
    bcrypt.genSalt(saltRounds, (err, salt) => {
        bcrypt.hash(req.app.locals.password, salt, async (err, hash) => {
            // Store hash in database here
            console.log(hash); // debug
            let post = {
                name: `${req.app.locals.name}`,
                email: `${req.app.locals.email}`,
                password: `${hash}`
            } // Структура данных для сервера
            let sql = "INSERT INTO users SET ?" // Writing data to the DB
            try {
                let query = await dbConnection.query(sql, post);
                return res.json({
                    "status": "ok",
                    "location": "galaktika-sluha.ml"
                });
            } catch (err) {
                console.log(err)
                res.json({
                    "status": "error",
                    "error": "Произошла ошибка сервера. Попробуйте позже"
                });
            }
        });
    });
});


Что делать?
  • Вопрос задан
  • 468 просмотров
Решения вопроса 1
yarkov
@yarkov
Помог ответ? Отметь решением.
Приучите себя всегда писать return res.json
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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