【问题标题】:How to intercept each and every req in express framework如何在express框架中拦截每个req
【发布时间】:2017-01-12 19:13:22
【问题描述】:

我希望在用户浏览我编写此代码的内容之前检查用户是否已通过身份验证。

router.use(function (req, res, next) {
    console.log(req);
    if(req.isAuthenticated()){
        console.log("if......");
        return next();
    }else{
        if (req.url === '/users/login' || req.url === '/users/register'){
            console.log("if......2");
            return next();
        }else{
            if (req.url === '/'){
                console.log("if......3");
                res.redirect('/users/register');
            }else{
                res.redirect('/users/login');
            }
        }
    }
});

现在我有两个问题要解决。

  1. 这是执行此操作的标准方法吗?不,请告诉我如何实现。
  2. 每当我浏览localhost:3000 我的req.url = /user/login 时,我也对此感到惊讶。我不知道这怎么可能。

但可能是缓存或不确定的东西我必须通知,在此之前我有一些类似下面的代码,旨在拦截或验证用户点击localhost:3000,但现在我已经评论了整个代码。

// Get Homepage
router.get('/'/*, ensureAuthenticated*/, function(req,res){
    res.render('index');
});

/*function ensureAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return next();
    }else{
        res.redirect('/users/login');
    }
}

router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});*/

【问题讨论】:

  • q 怎么样。 2
  • 另外,我建议你看看PassportJS的授权等情况。
  • 是的,我只使用 passportJs 来登录和所有
  • 第二个问题是关于调试的,你能把isAuthenticated函数中使用的代码展示一下吗?

标签: node.js express httprequest


【解决方案1】:

中间件在这里派上用场。 定义你的中间件像

module.exports.isAuthenticated=function(req,res,next){

  if(req.isAuthenticated){
  return next();
  }
  next(error('user is not authorized'));
}

然后在你的路由文件中

route.get('/home',auth.isAutheticated,goToHome);

【讨论】:

  • 你是对的,如果我这样做我需要为所有 req 做
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
  • 2020-11-30
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多