阻止节点js路由

我正在写节点的JS应用程序,我想阻止我的应用程序的一些url(closures所有用户)。 有可能吗? 注意:我想closures/注册和authentication。 更新:我使用express js框架

您可以创build一个可用于要阻止的路由的中间件:

var block = false; var BlockingMiddleware = function(req, res, next) { if (block === true) return res.send(503); // 'Service Unavailable' next(); }; app.get('/registration', BlockingMiddleware, function(req, res) { // code here is only executed when block is 'false' ... }); 

这显然是一个简单的例子。

编辑:更详细的例子:

 // this could reside in a separate file var Blocker = function() { this.blocked = false; }; Blocker.prototype.enableBlock = function() { this.blocked = true; }; Blocker.prototype.disableBlock = function() { this.blocked = false; }; Blocker.prototype.isBlocked = function() { return this.blocked === true; }; Blocker.prototype.middleware = function() { var self = this; return function(req, res, next) { if (self.isBlocked()) return res.send(503); next(); } }; var blocker = new Blocker(); var BlockingMiddleware = blocker.middleware(); app.get('/registration', BlockingMiddleware, function(req, res) { ... }); // to turn on blocking: blocker.enableBlock(); // to turn off blocking: blocker.disableBlock(); 

(这仍然引入了全局variables,但是如果你可以把决定你的“阻塞”条件的代码合并到阻塞类中,你可能会把它们除掉)