Block node route js

I am writing a node js application and I want to block some URLs in my application (disable for all users). Can this be done? Note. I want to disable registration and authentication. Update: I am using express js framework

+4
source share
1 answer

You can create middleware that you can use for the routes you want to block:

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 is a simple example, obviously.

EDIT: a more complex example:

// 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, , , )

+4

All Articles