在Express.js中使用会话 [英] Working with Sessions in Express.js

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

问题描述

我需要帮助了解Web应用程序的会话概念。我正在运行带有Express 3.0的Node.js服务器。



我的目标是:




  • 为登录的每个用户创建一个会话


  • 存储此会话并使用它来验证用户是否已经登录阻止两个设备同时使用同一个用户),并限制对某些页面的访问(通过将会话ID与某些其他数据相匹配)




我将使用MemoryStore保存会话(看起来最简单)。如果上述目标有意义,您可以提供一个如何实现这些目标的详尽解释?

解决方案

Express有不错的示例。其中一个涉及身份验证,并显示如何将用户附加到 req.session 对象。这是在 app.post('/ login')路线内完成的。



限制访问某些页面在这些路由中添加一个简单的中间件

  function restrict(req,res,next){
if(req.session .user){
next();
} else {
req.session.error ='Access denied!';
res.redirect('/ login');
}
}

app.get('/ restricted',restrict,function(req,res){
res.send('Wahoo!restricted area,点击< a href =/ logout> logout< / a>');
});

作为 Brandon 已经提到你不应该在生产中使用MemoryStore。 Redis 是一个很好的选择。使用 connect-redis 访问数据库。一个示例配置看起来像这样

  var RedisStore = require('connect-redis')(express); 

//将此添加到您的app.configure
app.use(express.session({
secret:kqsdjfmlksdhfhzirzeoibrzecrbzuzefcuercafafazewwzezejfxcerig,
store:new RedisStore主机:'localhost',port:3000,client:redis})
}));


I need help understanding the concept of sessions for a web application. I am running a Node.js server with Express 3.0.

My goals are to:

  • Create a session for each user that logs in

  • Store this session and use it for validating if the user is already logged in (prevent two devices using the same user at the same time) and to limit access to certain pages (by matching session ID to some other data)

I will be using MemoryStore to save the sessions (seems easiest). If the above goals make sense can you provide a thorough explanation of how to achieve them?

解决方案

Express has nice examples in the github repo. One of them deals with authentication and shows how to attach the user to the req.session object. This is done inside the app.post('/login') route.

To limit access to certain pages add a simple middleware to those routes

function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}

app.get('/restricted', restrict, function(req, res){
  res.send('Wahoo! restricted area, click to <a href="/logout">logout</a>');
});

As Brandon already mentioned you shouldn't use the MemoryStore in production. Redis is a good alternative. Use connect-redis to access the db. An example config looks like this

var RedisStore = require('connect-redis')(express);

// add this to your app.configure
app.use(express.session({
  secret: "kqsdjfmlksdhfhzirzeoibrzecrbzuzefcuercazeafxzeokwdfzeijfxcerig",
  store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
}));

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

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