如何使用express模块​​限制对node.js中许多文件夹的访问 [英] how to restrict access to many folders in node.js using express module

查看:63
本文介绍了如何使用express模块​​限制对node.js中许多文件夹的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js并将其表示为route方法,我的路由如下所示:

I am using node.js and express as the route method, my route looks like:

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

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

how can I set restrict access to 'public' and 'web' folders in one method, currently I am using two line, this code

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

推荐答案

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或下划线):

If you really want to make it fit in 1 line (dependent on lodash or underscore):

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

这篇关于如何使用express模块​​限制对node.js中许多文件夹的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆