阻塞节点js路由

Slo*_*rry 4 node.js express

我正在编写 Node js 应用程序,我想阻止我的应用程序上的一些 url(对所有用户关闭)。可以这样做吗?注意:我想关闭/打开注册和身份验证。 更新: 我使用express js框架

rob*_*lep 5

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

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'
  ...
});
Run Code Online (Sandbox Code Playgroud)

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

编辑:更详细的示例:

// 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();
Run Code Online (Sandbox Code Playgroud)

(这仍然引入了全局变量,但是如果您可以将确定“阻塞”条件的代码合并到类中,Blocker您可能可以摆脱它们)