NodeJS Express:如何中断外部中间件/路由器的路由?

我实现了一个非常简单的中间件来检查用户的权限:

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; } ... 

我发现中断stream程的最佳方式如下:

路线/ mycontroller.js

 router.get('/', function(req, res, next) { if(security.adminRequiredHtml()){return;} // now it actually interrupt the execution res.render('admin',{}); res.end(); }); 

不过,我想这样使用它:

路线/ mycontroller.js

 router.get('/', function(req, res, next) { security.adminRequiredHtml(); // <- interrupt the request res.render('admin',{}); res.end(); }); 

它正确执行redirect,但执行继续:(
我已经尝试了一些解决scheme,但它并没有真正的工作:
response.end() – >closures输出,但继续执行
process.end() – >它太激进,终止执行,但它也杀死服务器:(

我一直在考虑使用throw但我不知道在哪里捕捉它,并使其优雅地终止(没有堆栈跟踪)

我想,你实际上是在寻找中间件。

 function myMiddleware (req, req, next) { if (!isAdmin()) { res.redirect('/login'); res.end(); } else { //Proceed! next() } } router.get('/', myMiddleware, function(req, res, next) { res.render('admin',{}); res.end(); }); 

你可以链接尽可能多的,你想要处理任何你需要的逻辑。 只要确保你打电话next()如果你应该继续前进!

您可以创build一个安全的自定义路由器,并将您的安全路由添加到该路由:

 var secureRouter = express.Router(); // every request on this router goes throug this secureRouter.use('*', function (req, res, next) { if(isAdmin()) next(); // if you don't call next() you interrupt the request automaticly res.end(); }); // protected routes secureRouter.get('/user', function(req, res){/* whatever */}); secureRouter.post('/user', function(req, res){/* whatever */}); app.use(secureRouter); // not protected app.get('/api', function(req, res){/* whatever */}); 

使用中间件快速文档