【问题标题】:how to restrict access to many folders in node.js using express module如何使用 express 模块限制对 node.js 中许多文件夹的访问
【发布时间】:2014-09-08 20:39:41
【问题描述】:

我使用 node.js 和 express 作为路由方法,我的路由看起来像:

Set the website routes
app.use('/public', express.static('./public'));
app.use('/web', express.static('./web'));

如何在一种方法中设置对“public”和“web”文件夹的限制访问,目前我使用的是两行代码

app.get('/public*', checkPermissions, function(req,res,next){ next(); });
app.get('/web*', checkPermissions, function(req,res,next){ next(); });

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    checkPermissions 函数应如下所示:

    function checkPermissions(req, res, next) {
      // logic to check whether user has permissions or not.
      // example:
      if (req.user.permissions == 'admin') {
        next();
      } else {
        // redirect if user doesn't have permission.
        res.redirect('/no-permissions');
      }
    }
    

    如果你真的想让它适合 1 行(取决于 lodash 或下划线):

    _.(['/public*', '/web*']).each(function(route) {
      app.get(route, checkPermissions, function(req, res, next) { next(); });
    });
    

    【讨论】:

    • 我的问题不在“checkPermissions”函数中,我在问如何使用一行而不是两行来限制两个文件夹
    • 你为什么要这样做?
    • 因为我的服务器中有很多文件夹,其中一些共享相同的权限,有些没有,所以,我想将相似权限的文件夹分组在一行中,而不是有很多重复的行跨度>
    猜你喜欢
    • 2016-05-16
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多