sailsjs policy causing Can't set headers after they are sent error

本小妞迷上赌 提交于 2019-12-12 03:09:39

问题


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?


回答1:


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

        });
};


来源:https://stackoverflow.com/questions/28528907/sailsjs-policy-causing-cant-set-headers-after-they-are-sent-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!