您可以创建一个可用于要阻止的路由的中间件:
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您可能可以摆脱它们)
| 归档时间: | 
 | 
| 查看次数: | 2745 次 | 
| 最近记录: |