sailsjs策略导致发送标头后无法设置错误
我有这个政策,基本上是在允许用户使用对象之前,先检查用户对对象的访问.因此,用户1是否有权访问事件4以便进行/event/edit/4这样的操作.
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.
我尝试创建策略(我已经编辑了顶部,所以如果其中有错误,请相信我应该在应有的情况下运行return res.direct),但是当达到正确条件时,帆流程就开始了死于发送后无法设置标题"的错误.
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();
};
我也尝试过返回res.forbidden('不允许您执行此操作.'),而不是res.redirect.并不是说这会有所作为,但我必须指出我在那儿做错了事.
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?
问题是您的查找是异步操作.这意味着首先将触发find(),然后其余中间件函数将运行,包括return next().之后,您的find()将返回并触发res.redirect(),从而导致错误.您需要对代码进行结构化,以使所有代码都位于回调内部:
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();
});
};