【发布时间】:2016-04-07 23:35:34
【问题描述】:
我实现了一个非常简单的中间件来检查用户的权限:
app.js
...
var security = require('./lib/security');
app.use(security.init);
...
lib/security.js
var session;
var request;
var response;
function init(req, res, next) {
request = req;
response = res;
session = req.session;
next();
}
function adminRequired(){
if (!isAdmin()){
response.redirect('/login');
response.end();
return true;
}
return false;
}
...
我发现中断流程的最佳方法如下:
routes/mycontroller.js
router.get('/', function(req, res, next) {
if(security.adminRequiredHtml()){return;} // now it actually interrupt the execution
res.render('admin',{});
res.end();
});
但是,我想这样使用它:
routes/mycontroller.js
router.get('/', function(req, res, next) {
security.adminRequiredHtml(); // <- interrupt the request
res.render('admin',{});
res.end();
});
它正确执行了重定向,但执行仍在继续:(
我已经尝试了一些解决方案,但它并没有真正起作用:response.end() -> 关闭输出但继续执行process.end() -> 它太激进了,终止执行但它也会杀死服务器:(
我一直在考虑使用 throw,但我不知道在哪里捕获它并让它优雅地终止(没有堆栈跟踪)
【问题讨论】:
-
它不优雅,可能会导致混淆(并因此导致安全流程),因为浏览器上的结果是正确的,但执行仍在继续。