【问题标题】:How to Enable/Disable session based on url using nodejs?如何使用nodejs基于url启用/禁用会话?
【发布时间】:2020-11-28 15:49:53
【问题描述】:

我使用 express 和 express-session 中间件来构建一个启用会话的网站。但是一些url比如/health-check' and/version-checkdo not need session, especially the/health-check`,会在db中产生很多无用的session(项目使用mongodb)。相信有很好的解决方法。

以下是会话的sn-ps:

var session = require('express-session'),
    passport = require('passport');

var app = express();
//other middleware.

// Express MongoDB session storage
app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    cookie: { maxAge: 2628000000 },
    store: new mongoStore({
        db: db.connection.db,
        collection: config.sessionCollection
    })
}));

// use passport session
app.use(passport.initialize());
app.use(passport.session());
//...

【问题讨论】:

    标签: node.js session express


    【解决方案1】:

    我建议创建自己的中间件函数并将您的会话中间件作为函数放在那里,但有条件,例如:

    app.use(function(req, res, next){
      if(...some condition...){//for example check url
        //do something or nothing
        next();//very important or request will freeze
      } else {//otherwise run session
        session({your options})(req, res, next);
      }
    });
    

    而不是你的 app.use(session())

    在一个自定义中间件中,您可以放置​​任何其他中间件来添加条件。但是,当您想将多个中间件包装到单个自定义中间件时,请注意“下一步”。在中间件中只能使用一次(多个中间件多次使用)。然后你必须创建你自己的回调'next'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2015-03-10
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2012-01-05
      相关资源
      最近更新 更多