Nicholas McNary Nicholas McNary - 1 month ago 4
Javascript Question

Nodejs/Express - Error: Can't set headers after they are sent

Pretty new to node/express. I'm checking to see if the user (via the username) already exists in the database that one wants to register to, giving an error if they do already exist.

When I use curl to try to set it off intentionally, I get the following error:


Error: Can't set headers after they are sent.


I know already that the first check I do to ensure that all the fields are filled in works correctly, and provides no issues with headers being set multiple times.

Any help would be greatly appreciated.

(My relevant code is below. If you need anything else, feel free to say so!)

router.post('/register', function(req, res, next) {
if(!req.body.username || !req.body.password){
return res.status(400).json({ message: 'Please fill out all fields.' });
}

User.count({ username: req.body.username}, function(err, count){
console.log(count);
if(count > 0) {
return res.status(400).json({message: 'This user already exists!' });
}
});

var user = new User();

user.username = req.body.username;
user.setPassword(req.body.password);

user.save(function(err) {
if(err) { return next(err); }

return res.json({ token: user.generateJWT()});
});
});

Answer

When you are returning inside User.count and user.save, you are returning only from inside the callbacks but not the entire method.

Its a good practice to send a response in just one place. At the end of the method. Before that evaluate your conditions and set the response code and response message in some variable. Which you can use to send the response as a final step.

Try this as a workaround for now:

    router.post('/register', function(req, res, next) 
{
    if(!req.body.username || !req.body.password)
    {
        return res.status(400).json({ message: 'Please fill out all fields.' });
    }

    User.count({ username: req.body.username}, function(err, count)
    {
        console.log(count);
        if(count > 0) 
        {
            return res.status(400).json({message: 'This user already exists!' });
        }
        else
        {
            var user = new User();
            user.username = req.body.username;
            user.setPassword(req.body.password);

            user.save(function(err) 
            {
                if(err) 
                { 
                    return next(err); 
                }

                return res.json({ token: user.generateJWT()});
            });
        }
    });
});
Comments