[英]Block node js route
I am writing node js app and I want to block some urls on my app (turn off for all users). 我正在编写节点js应用程序,我想阻止我的应用程序上的一些网址(关闭所有用户)。 Is it possible to do so?
有可能这样做吗? Note: I want to switch off/on registration and authentication.
注意:我想关闭/开启注册和身份验证。 Update: I use express js framework
更新:我使用快递js框架
You can create a middleware that you can use for the routes that 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 just a simple example, obviously. 显然,这只是一个简单的例子。
EDIT: more elaborate 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();
(this still introduces global variables, but if you can merge the code that determines your 'blocking' condition into the Blocker
class you can probably get rid of them) (这仍然会引入全局变量,但是如果你可以将确定你的'阻塞'条件的代码合并到
Blocker
类中,你可以将它们删除掉)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.