Node.js Express-阻止访问某些URL [英] Node.js Express - prevent access to certain URLs

查看:84
本文介绍了Node.js Express-阻止访问某些URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止访问未登录到以'/users'开头的任何URL的人

这是我当前的代码:

  app.use('/^ users *',function(req,res,next){如果(checkAuth(req)){console.log('授权确定');下一个();} 别的 {console.log('授权失败');res.redirect('/login');}});函数checkAuth(req){console.log('req',req.url);如果(!req.session.user_id&& req.url!=='/login'&& req.url!=='/'){返回false;}返回true;}; 

但是我使用的正则表达式不正确.我找不到匹配以'user'开头的所有内容"的正则表达式.这应该很容易,但是事实证明比预期的要困难.

根据Express API文档:

 //将匹配以/abcd开头的路径app.use('/abcd',函数(req,res,next){下一个();}) 

解决方案

  app.all('*/users/*',requireAuthentication,function(req,res,next){}); 

上述路由将捕获从用户开始的所有类型的请求,将通过 requireAuthentication 函数,然后在 next()上跟随函数./p>

I want to prevent access to someone not logged-in to any url that starts with '/users'

Here's my current code:

app.use('/^users*',function (req, res, next) {
    if (checkAuth(req)) { 
        console.log('authorization OK');
        next(); 
    } else {
        console.log('authorization failed');
        res.redirect('/login');
    }

});

function checkAuth(req) {
    console.log('req',req.url);
    if (!req.session.user_id && req.url !== '/login' && req.url !== '/') {
        return false;
    }
    return true;
};

but the regular expression I have is not right. I can't find a regular expression for expression that matches "everything that starts with 'user'". This should be easy, but is proving more difficult than expected.

According to the Express API documentation:

// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
  next();
})

解决方案

app.all('*/users/*', requireAuthentication, function (req, res, next){

});

Above route will catch all kind of requests starting from users, will through requireAuthentication function, then following function on next().

这篇关于Node.js Express-阻止访问某些URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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