0
votes

I'm following a course about node.js on Udemy which is kinda outdated and came across these errors which I'm unable to find a solution for.

What I tried:

  • using next();
  • adding return res inside all if statements

Can someone help me fix these? I would greatly appreciate it!

Thanks in advance!

Username exists error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11) at ServerResponse.header (C:\Users\Documents\projects\chat-app\chat-app-backend\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\Documents\projects\chat-app\chat-app-backend\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\Documents\projects\chat-app\chat-app-backend\node_modules\express\lib\response.js:267:15)
at C:\Users\Documents\projects\chat-app\chat-app-backend\controllers\auth.js:38:56 at processTicksAndRejections (internal/process/task_queues.js:97:5) { code: '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'});
            });
        });
    }
}
1
you are trying to send response twice, thats the reason you are facing this error - Narendra Chouhan

1 Answers

1
votes

You're executing some promise and don't wait for the answer before executing the next code....

There are many ways to handle this, this next code is just one way...

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