setheader给出错误:“抛出新错误('不能在发送后设置标题。');”

时间:2014-01-28 11:29:50

标签: node.js express sails.js

在检查用户是否已投票时获取此错误。我建议setheader事情是负责任的。

CODE

index : function(req, res, next){ 
    if(req.method == "POST"){
        var aa =  Users.findOneByEmail(req.param('email'), function(err, data, next){
            if(err) res.serverError(err);
            console.log(data);
            if(data){
                res.redirect('/users');
                return;
            }
        });

        var data = {
            remoteip:  req.ip,
            challenge: req.body.recaptcha_challenge_field,
            response:  req.body.recaptcha_response_field
        };

        // console.log(data);
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY,  data);
        recaptcha.verify(function(success, error_code) {
            if(!success){
                return res.serverError(error_code)              
            } else {
                var username =  req.param('username');
                var vote =  req.param('vote');
                var email = req.param('email');
                var reason =  req.param('reason');
                console.log('I am here 2');
                Users.create({
                    username: req.param('username'),
                    email: email,
                    candidate_id : vote,
                    reason : reason
                }).done(function(err, data){
                    if(err){
                        return res.serverError(JSON.stringify(err));
                    } else {
                        return res.send('You sucessfully voted');
                    }
                });
            }

            res.redirect('/candidates/');
        });          
    } else {
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY);
        Candidates.find().done(function(err, data){
            res.view({candidates : data, recaptcha_form: recaptcha.toHTML()});
        });
    }
},

错误:

http.js:691     
    throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
    at ServerResponse.res.setHeader (/usr/local/lib/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:59:22)
    at ServerResponse.res.set.res.header (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:522:10)
    at ServerResponse.res.location (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:656:8)
    at ServerResponse.res.redirect (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:698:8)
    at /Users/korotane/Documents/node_projects/the_next_indian_pm/api/controllers/UsersController.js:75:14
    at IncomingMessage.<anonymous> (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/recaptcha/lib/recaptcha.js:160:20)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickDomainCallback (node.js:459:13)

2 个答案:

答案 0 :(得分:3)

看看第4行:

if(err) res.serverError(err);

问题是,res.serverError已经发送了标头,因此,由于您没有中断对它的执行,以下任何调用都可能导致您的错误:res.serverError, res.send, res.redirect

在您的特定情况下,它是重定向。回溯中的相应行:

...
at ServerResponse.res.redirect (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:698:8)
...

长话短说,快速解决方法是将return添加到第四行:

if (err) return res.serverError(err);

那就是说,不能保证其他一切都能无缝地发挥作用。

答案 1 :(得分:0)

在复杂的代码中,只要您想在许多场合发送响应 你可以检查res.headersSent是假的。

IE:如果(res.headersSent){res.send()}

如果您在发送响应之前使用“return”,那么代码将不会再执行。