块节点js路由

时间:2013-11-07 08:49:50

标签: node.js express

我正在编写节点js应用程序,我想阻止我的应用程序上的一些网址(关闭所有用户)。有可能这样做吗?注意:我想关闭/开启注册和身份验证。 的更新 我使用express js framework

1 个答案:

答案 0 :(得分:4)

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

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();

(这仍然会引入全局变量,但如果您可以将确定“阻塞”条件的代码合并到Blocker类中,则可以将它们删除掉)

相关问题