1. 程式人生 > >關於NodeJS 的Session模組-一應用Express

關於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 presents a 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 of connect-redis you 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:[email protected]:27017/3xam9l3'
  }),
  secret: '1234567890QWERTY'
}));

//...

It is honestly that simple. Of course there are a lot more options 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.