【问题标题】:nodejs, how to check if session is defined on every pagenodejs,如何检查是否在每个页面上都定义了会话
【发布时间】:2012-12-06 04:27:53
【问题描述】:

我正在使用 express 开发一个简单的网站。 我只是对如何在渲染任何页面之前让 nodejs 检查会话感到困惑,这样如果用户没有登录,他就看不到任何东西。

我认为在 Rails 中这很简单,只需在应用程序控制器中添加一些代码即可。但是如何在 nodejs 中处理这样的事情呢?

【问题讨论】:

    标签: node.js session express


    【解决方案1】:

    定义一个中间件函数以在您的路由之前检查身份验证,然后在您的每个路由上调用它。例如在您的 app.js 中

    // Define authentication middleware BEFORE your routes
    var authenticate = function (req, res, next) {
      // your validation code goes here. 
      var isAuthenticated = true;
      if (isAuthenticated) {
        next();
      }
      else {
        // redirect user to authentication page or throw error or whatever
      }
    }
    

    然后在你的路由中调用这个传递这个方法(注意 authenticate 参数):

    app.get('/someUrl', authenticate, function(req, res, next) {
        // Your normal request code goes here
    });
    
    app.get('/anotherUrl', authenticate, function(req, res, next) {
        // Your normal request code goes here
    });
    

    【讨论】:

    • 是的——这就是处理它的方法。我唯一的批评是,正如所写的那样,您将authenticate 泄漏到全球范围内。使用var 或只写function authenticate(req, res, next) { ... 以保持其范围为模块。
    • 但是,我应该如何保护静态的东西呢?就像我的主页被重写为 index.html
    • @YitongZhou:如果你想为每个请求运行你的函数,只需将它交给app.use而不是在路由处理程序中。 (当然,现在您必须确保您的函数跳过对登录页面及其相关资源的检查,这可能会很棘手。)
    • 有没有其他方法可以在一个地方检查每个请求,而不是在每个请求上添加authenticate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2011-06-10
    相关资源
    最近更新 更多