在一组路由上激活了Express.js会话 [英] Express.js sessions activated on a subset of routes

查看:142
本文介绍了在一组路由上激活了Express.js会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用expressjs,并希望使用会话验证用户的登录。网站/应用程序一方面允许用户在无状态网页中浏览和调查不同的产品和信息,从而允许对这些页面进行缓存,但另一方面应具有让用户登录并访问使用会话获取的不同内容的功能

I'm working with expressjs and want to authenticate users for a login using sessions. The site/app should on one hand allow the user to browse and investigate different products and information in a stateless webpage allowing caching of these pages, but should on the other hand have the functionality to let the user login and access different content acquired using sessions.

因此,对于我的路线的一个子集,我希望会话状态被激活,而对于互补子集(我的其余路由),表示会话应该被停用,允许缓存这些页面。

Thus for a subset of my routes I want session state activated, while for the complementary subset (the rest of my routes) express sessions should be deactivated, allowing caching of these pages.

如何以干净的方式这样做?

How can I do this in a clean way?

说出我想要的路线激活会话是'/ kj%C3%B8p','/ bibliotek'和'/ register'。

Say the routes for which I want to activate sessions are '/kj%C3%B8p', '/bibliotek' and '/register'.

我尝试过像

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');

  var pageName = 'somepage';
  var oneYear = 1000*60*60*24*365;
  app.use(express.bodyParser());
  app.use('/kj%C3%B8p', express.cookieParser());
  app.use('/kj%C3%B8p', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path:'/', maxAge: (5*oneYear), httpOnly: true}}));
  app.use('/bibliotek', express.cookieParser());
  app.use('/bibliotek', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path: '/', maxAge: (5*oneYear), httpOnly: true}}));
  app.use('/registrer', express.cookieParser());
  app.use('/registrer', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path:'/', maxAge: (5*oneYear), httpOnly: true}}));

  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));

});

但这会重新生成三个路由中的每个路由的会话对象,似乎相当凌乱。任何提示?

but this regenerates the session object for each of the three routes, and seems quite messy. Any tips?

推荐答案

您可以将功能中的中间件包装到黑名单或白名单中。这是一个白名单的例子:

You can wrap middleware in a function to black or whitelist certain urls. This is a whitelist example:

function allow(paths, fn) {
  return function(req, res, next) {
    if (~paths.indexOf(req.url)) {
      return fn(req, res, next);
    }
    next();
  }
}

将其包裹在您的中间件上,如:

You wrap it around your middleware like:

app.use(allow(['/bibliotek', '/registrer'], express.cookieParser()));

您可以对其他中间件使用相同的技术。这是基于快速作家在irc显示的要点

You can use the same technique for other middleware as well. This was based on a gist that the express author showed in irc.

这篇关于在一组路由上激活了Express.js会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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