gpt4 book ai didi

node.js - NodeJS express : How to interrupt the routing from outside the middleware/router?

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:24 26 4
gpt4 key购买 nike

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

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 但我不知道在哪里捕获它并让它优雅地终止(没有堆栈跟踪)

最佳答案

您可以创建一个安全的自定义路由器并将您的安全路由添加到其中:

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 */});

Express doc for using middlewares

关于node.js - NodeJS express : How to interrupt the routing from outside the middleware/router?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com