`
xidajiancun
  • 浏览: 455855 次
文章分类
社区版块
存档分类
最新评论

关于NodeJS 的Session模块-一应用Express

 
阅读更多

首先呢这是一篇翻译或来的文章,文章内容讲的很详实,比国内文章强一些。英语水平有限,错误之处还需订正,希望对大家有些帮助,

Using sessions to keep track of users as they journey through your site is key to any respectable application. Luckily, as usual, using Express with your Node.js application makes it super simple to get sessions up and running.

使用Session是我们在追踪用户在他们使用应用程序的时候我们能够准确掌握其操作的关键。幸运的是,像往常一样,在Node.js之中套用框架Express(点击打开链接)能够让我们超级简单的操作Session和运行程序。

Express App

Before we do anything else, we need an Express application. Creating an Express app is extremely simple, and the makers of Express do a pretty good job documenting the process.

在我们做任何事情之前,我们需要一个Express的应用程序。创建一个express应用程序是极其简单的。而且Express框架的作者为该框架已经为我们学习该框架准备了丰富的文档和学习指南,一下是Express的一个示例:

package.json

{
  "name": "SessionsExample",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x"
  }
}

app.js

var express = require('express');
var app = express();

app.get('/awesome', function(req, res) {
  res.send("You're Awesome.");
});

app.get('/radical', function(req, res) {
  res.send('What a radical visit!');
});

app.get('/tubular', function(req, res) {
  res.send('Are you a surfer?');
});

//If you host the application on Modulus the PORT environment variable will be defined,
//otherwise I’m simply using 8080.
app.listen(process.env.PORT || 8080);

Now we have three routes defined and available to visit. If you visit one page, it's like you are visiting it for the first time. However, what if we wanted to remember the last page someone visited? We can easily do that with sessions.

现在我们已经定义了三个路由并能够访问,假如你想访问其中一个页面,就像其他第一次访问页面一样。然而,我们想记住最后一次访问的页面该怎么办?我们可以使用Session很简单的解决该问题。

Remembering Things

Before we dive in, there is a little bit of setup necessary. We need to “use” the cookie parser and the session features of express before the sessions will be made available. You do this before you define any routes, which in our case would look like so:

在我们使用Session时,我们需要做一些必须的工作,我们需要使用"use"方法去定义中间件cookieParser和Sesion遮掩才能正确使用Express提供的Session功能。你必须在你定义路由之前做那些工作。下面使我们写完成的例子:

app.js

var express = require('express');
var app = express();

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));

app.get('/awesome', function(req, res) {
  res.send('Your Awesome.');
});

app.get('/radical', function(req, res) {
  res.send('What a radical visit!');
});

app.get('/tubular', function(req, res) {
  res.send('Are you a surfer?');
});

app.listen(process.env.PORT || 8080);

Since sessions use cookies to keep track users we need both the cookie parser and the session framework. It is important to note that the cookie parser is used before the session, this order is required for sessions to work.

既然sessions使用cookies去追踪用户,那这样我们需要cookieparser和session框架,这非常重要在我们使用session让其工作之前要先去定义cookieparser。

We also provide a secret to the session initializer, which provides a little more security for our session data. Of course you might what to use a key that is a little more secure.

我们也提供了一个加密秘钥在我们session初始化的时候,让其为我们的session数据提供一些安全,当然,你也可以使用一个秘钥来保证一定的安全性。

Sessions are accessible through the request object in each route. You can get and set properties just like you would when handling an object normally. For example, lets set some session data in the awesome route.

Session是可以在每一个路由请求通过request对象能够轻易地获取。你能够像你处理普通对象那样来获取和设置session里面的属性内容。

例如,让我们在“/awesome”的路由请求中设置一些session数据

app.get('/awesome', function(req, res) {
  req.session.lastPage = '/awesome';
  res.send('Your Awesome.');
});

It really is as easy as accessing the session object in the request. Let’s say we want to print the last page the user visited as well.

app.get('/awesome', function(req, res) {
 if(req.session.lastPage) {
   res.write('Last page was: ' + req.session.lastPage + '. ');
 }

 req.session.lastPage = '/awesome';
 res.send('Your Awesome.');
});

Lastly we can apply this to the rest of the routes.

var express = require('express');
var app = express();

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));

app.get('/awesome', function(req, res) {
  if(req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }

  req.session.lastPage = '/awesome';
  res.send('Your Awesome.');
});

app.get('/radical', function(req, res) {
  if(req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }

  req.session.lastPage = '/radical';
  res.send('What a radical visit!');
});

app.get('/tubular', function(req, res) {
  if(req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }

  req.session.lastPage = '/tubular';
  res.send('Are you a surfer?');
});

app.listen(process.env.PORT || 8080);

And there it is, a session enabled application.

ok,就是这样,一个session可用的应用程序

Using Redis

There is only one major issue with our sessions. Anytime we restart our app, all of the user sessions are lost. I think we can all agree this presentsa problem with our updating process.

现在只有一个很严重的问题。那就是无论何时我们重启程序,所有用户的session数据都会丢失,我认为我们完全认同在进步过程中这个目前的难题。

There are several ways around this problem, but one of the best ways is to use an external store for the session data. More specifically, we can use a Redis store. This way the session data is completely separate from our running application.

关于这个难题有好几种解决方式,但是其中最好的一个方式是为session数据使用扩展的存储方式。更好的方式是,我们可以使用一个Redis 存储,使用这种方式我们完全可以将session数据存储和应用程序本身分割开来,而不依赖与浏览器等宿主环境。

To set up Redis with Express sessions, we need an extra module. This module is the Redis client used by connect and helps create a streamlined solution for connecting Redis to Express. First we have to make sure its in our package.json.

为了在Express session中设置Redius,我们需要额外的模块,这个模块是通过Redis客户端进行联系的而且帮助创建一个为连接Redis和Express的最新型的解决方案。首先第一格我们需要设置一下我们的package.json文件

package.json

{
  "name": "SessionsExample",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x",
    "connect-redis": "1.4.x"
  }
}

Then we have to require it.(包含进来文件)

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

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));

//...

Notice that we pass Express to the Redis connector. This is required for Express and the Redis store to play nice with each other, which makes the process a whole lot easier later.

注意我们传递了Express对象给了Redis 连接。这是为了使Express和Redis两者能够后互相协调的工作,这个使得整个过程更加的容易。

In order to set up the Redis store with our sessions, we are going to modify our app.use call. The session initializer not only takes a secret, but a store as well. As you can probably guess, this is used to tell the session manager where to put all the session data. All we have to do is pass in an object it can use instead of its native storage.

为了建立Redis来存储我们的session。我们需要改变我们的调用方式。这个session初始化不仅仅是设置一个secret,而且也是初始化了存储模块。这样你可能才想到,这个是用来告诉session管理模块应该把这些session数据存放在哪个地方。仅需要我们所做的是传递一个对象来代替我们本地存储

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

app.use(express.cookieParser());
app.use(express.session({
  store: new RedisStore({
    host: 'localhost',
    port: 6379,
    db: 2,
    pass: 'RedisPASS'
  }),
  secret: '1234567890QWERTY'
}));

//...

It’s as simple as that. The RedisStore constructor can take all the normal options you would expect. In this case we are going to use database 2 with the password we use to authenticate with our Redis instance.

看起来如此简单。这个RedisStore构造函数可以设置所有的你所希望设置的值。在这种情况下,我们可以我们可以使用数据库2并捎带着权限的密码在我们的Redis实例中。

Now all of our session data will stored safely in our Redis database. This also means that any time we restart our node application, the session data is immune from being reset because it is not stored under the same process as our application.

现在所有的我们的session数据可以安全的存储在Redis数据库里,这个也意味着我们可以在任何时候启动我们的node应用程序是的时候,这些session数据也不会被重置。这是因为他没有被存储在我们的程序进程之中。

What about Mongo?

So some of you out there might be wondering if you can use MongoDB to store your session data. Well, using Mongo in place of Redis in our previous example is actually just as simple as using Redis. Instead ofconnect-redisyou just use, you guessed it,connect-mongo.

这里面的我们很多会为什么不用M哦你goDB来存储我们的session数据,好吧,使用Mongo来代替Redis是我们的上一个例子其结果两者是一样的简单,两者使用可以根据需要来选择。

package.json

{
  "name" : "SessionsExample",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.x",
    "connect-mongo" : "0.3.x"
  }
}

Just add a few “Mongo”s where you see “Redis” and it all falls into place.

var express = require('express');
var app = express();
var MongoStore = require('connect-mongo')(express);

app.use(express.cookieParser());
app.use(express.session({
  store: new MongoStore({
    url: 'mongodb://root:myPassword@mongo.onmodulus.net:27017/3xam9l3'
  }),
  secret: '1234567890QWERTY'
}));

//...

It is honestly that simple. Of course there area lot moreoptions you have when creating your MongoStore instance, but the example above gets you the basic functionality and will start storing your session data in your Mongo database.

So there are the basics behind Express sessions. As you can see, it is not complicated, and just requires a little setup to get rolling. Don’t forget, if you have any questions or comments, throw them out below. We are never afraid of feedback.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics