Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

node.js - sailsjs policy causing Can't set headers after they are sent error

I have this policy that basically checks a users access to an object before allowing them to do anything with it. So, does user 1 have access to event 4 in order to /event/edit/4 kind of thing.

I tried creating a policy (I've edited the top part, so if there are errors in this, trust me that it runs the return res.direct when it's supposed to) but when it hit's the right condition the sails process dies with an error of "Can't set headers after they are sent."

I took out another policy that was being triggered to see if it was doing anything, but it didn't change anything. Here's my policy:

module.exports = function(req, res, ok) {
    MyObj.find(req.param('id'))
        .exec(function getObjects(err, objects){
            if (objects[0]["parent"]["user"] != req.session.User.id) {  
                req.session.flash = {
                    err: "woops!"
                }
                return res.redirect('/');
            }
        });

    res.locals.flash = {};
    if(!req.session.flash) return ok();
    res.locals.flash = _.clone(req.session.flash);
    req.session.flash = {};
    return next();
};

I've also tried return res.forbidden('You are not permitted to perform this action.') instead of the res.redirect. Not that it would make a difference, but I had to factor out that I was doing the wrong thing there.

Anyone see why it would give me that error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that your find is an asynchronous operation. Meaning that first, find() will trigger, then the rest of your middleware function will run including return next(). After which your find() will return and trigger res.redirect(), hence causing the error. You need to structure your code so that all of it is inside the callback:

module.exports = function(req, res, ok) {
    MyObj.find(req.param('id'))
        .exec(function getObjects(err, objects){
            if (objects[0]["parent"]["user"] != req.session.User.id) {  
                req.session.flash = {
                    err: "woops!"
                }
                return res.redirect('/');
            }

            res.locals.flash = {};
            if(!req.session.flash) return ok();
            res.locals.flash = _.clone(req.session.flash);
            req.session.flash = {};
            return next();

        });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...