简体   繁体   English

Node.js / Express-错误:发送标头后无法设置标头

[英]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: 当我使用curl故意将其设置为关闭时,出现以下错误:

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

When you are returning inside User.count and user.save, you are returning only from inside the callbacks but not the entire method. 当您在User.count和user.save内部返回时,您仅从回调内部返回,而没有从整个方法中返回。

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

Put all your code in the callback function of User.count, otherwise the two part of code are executed 将所有代码放入User.count的回调函数中,否则将执行代码的两部分

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM