【问题标题】:Node.js Cannot set headers after they are sent to the clientNode.js 发送到客户端后无法设置标头
【发布时间】:2020-09-05 09:15:18
【问题描述】:

我正在 Udemy 上学习关于 node.js 的课程,该课程有点过时,并且遇到了这些我无法找到解决方案的错误。

我尝试了什么:

  • 使用 next();
  • 在所有 if 语句中添加 return res

有人可以帮我解决这些问题吗?我将不胜感激!

提前致谢!

用户名存在错误:错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头 在 ServerResponse.setHeader (_http_outgoing.js:526:11) 在 ServerResponse.header (C:\Users\Documents\projects\chat-app\chat-app-backend\node_modules\express\lib\response.js:771:10) 在 ServerResponse.send (C:\Users\Documents\项目\chat-app\chat-app-backend\node_modules\express\lib\response.js:170:12)
在 ServerResponse.json (C:\Users\Documents\projects\chat-app\chat-app-backend\node_modules\express\lib\response.js:267:15)
在 C:\Users\Documents\projects\chat-app\chat-app-backend\controllers\auth.js:38:56 在 processTicksAndRejections (internal/process/task_queues.js:97:5) { 代码:'ERR_HTTP_HEADERS_SENT' }

module.exports = {
    CreateUser(req, res) {

        const schema = Joi.object().keys({
            username: Joi.string().min(5).max(15).required(),
            email: Joi.string().email().required(),
            password: Joi.string().min(5).required()
        });

        const {error, value} = Joi.validate(req.body, schema);

        if (error && error.details) {
            return res.status(HttpStatus.BAD_REQUEST).json({message: error.details});
        } 

        async function EmailExists() {
            return await User.findOne({email: Helpers.lowerCase(req.body.email)}) != undefined;
        }

        async function UsernameExists() {
            return await User.findOne({username: Helpers.firstLetterUppercase(req.body.username)});
        }

        EmailExists().then(exists => {
            if (exists) {
                return res.status(HttpStatus.CONFLICT).json({message: 'Email already exists'});
            }
        }).catch((err) => console.log('Email exists error: ', err));

        UsernameExists().then(exists => {
            if (exists) {
                return res.status(HttpStatus.CONFLICT).json({message: 'Username already exists'}) != undefined;
            }
        }).catch((err) => console.log('Username exists error: ', err));


        return BCrypt.hash(value.password, 10, (error, hash) => {
            if (error) {
                return res.status(HttpStatus.BAD_REQUEST).json({message: 'Error hashing password'});
            }

            const body = {
                username: Helpers.firstLetterUppercase(value.username),
                email: Helpers.lowerCase(value.email),
                password: hash
            };

            User.create(body).then((user) => {
                res.status(HttpStatus.CREATED).json({message: 'User created successfully'});
            }).catch((err) => {
                res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({message: 'Something went wrong. Could not save user'});
            });
        });
    }
}

【问题讨论】:

  • 您尝试发送两次响应,这就是您遇到此错误的原因

标签: javascript node.js express mongoose


【解决方案1】:

你正在执行一些承诺,在执行下一个代码之前不要等待答案......

有很多方法可以处理这个问题,下面的代码只是一种方法......

    const hash = () => BCrypt.hash(value.password, 10, (error, hash) => {
        if (error) {
            return res.status(HttpStatus.BAD_REQUEST).json({message: 'Error hashing password'});
        }

        const body = {
            username: Helpers.firstLetterUppercase(value.username),
            email: Helpers.lowerCase(value.email),
            password: hash
        };

        User.create(body).then((user) => {
            res.status(HttpStatus.CREATED).json({message: 'User created successfully'});
        }).catch((err) => {
            res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({message: 'Something went wrong. Could not save user'});
        });
    });


    EmailExists().then(exists => {
        if (exists) {
            return res.status(HttpStatus.CONFLICT).json({message: 'Email already exists'});
        }

           UsernameExists().then(exists => {
                if (exists) {
                   return res.status(HttpStatus.CONFLICT).json({message: 'Username already exists'}) != undefined;
                }

                return hash();
           }).catch((err) => console.log('Username exists error: ', err));          


    }).catch((err) => console.log('Email exists error: ', err));

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2021-09-11
    • 2018-05-25
    • 2021-06-27
    • 2021-06-18
    • 2019-05-17
    • 2023-03-29
    • 2020-11-14
    相关资源
    最近更新 更多