Node.js: Cookie and Session

Cookie and Session。

補充說明

外部認證

將 Cookie 保密是一個使得 Cookie 安全的必要方法,我們可以使用 xkcd Password Generator或憑證來保障其安全性。這裡選用憑證。建立一個 JavaScript 檔案 - credential.js,將憑證存放在這支檔案裡面。記得,要加到.gitignore,使其不受版本控管。

credential.js 部份。

module.exports = {
  cookieSecret: 'your cookie secret goes here',
};

app.js 部份。

var credentials = require('./credential.js');
npm install --save cookie-parser

在 app.js 中設定載入模組 cookie-parser

var cookieParser = require('cookie-parser');
app.use(cookieParser(credentials.cookieSecret));

假設在取得首頁時,設定兩組 Cookie:monster 和 signed_monster。

// get index page
router.get('/', function(req, res, next) {
  // 取得各城市的氣象相關資訊
  if (!res.locals.partials) {
    res.locals.partials = {};
  }
  res.locals.partials.weather = getWeatherData();

  // 取得首頁時,設定兩組Cookie:monster和signed_monster
  res.cookie('monster', 'nom nom');
  res.cookie('signed_monster', 'nom nom', { signed: true });
  res.render('index', { title: 'Index' });
});

來看看結果。

Node - Cookie and Session

將剛剛設定的 Cookie 從 Server 端讀取。

var monsterCookie = req.cookies.monster;
var signedMonsterCookie = req.signedCookies.signed_monster;

刪除 monster 這個 Cookie。

res.clearCookie('monster');

Session

使用一個內含獨一無二識別碼的 Cookie,Server 端會用這個識別碼來取回適當的 Session 資訊。

安裝並設定 express-session

npm install --save express-session

在 app.js 中設定載入模組 express-session。

var credentials = require('./credential.js'),
    session = require('express-session');

app.use(cookieParser(credentials.cookieSecret));
app.use(session());

使用 Session

req.session.userName = 'Pusheen';
var colorScheme = req.session.colorScheme || 'dark';

console.log(req.session.userName); // Pusheen
console.log(colorScheme); // Dark

delete req.session.userName; // remove session
console.log(req.session.userName); // undefined

補充說明

使用 Session 來實作閃爍訊息

於是我們就可以利用 Session 來實作在Node.js:表單處理與檔案上傳(Form Handling and File Uploads)提到的,當使用者提交表單後,直接在頁面上顯示 Flash 訊息來提示使用者成功送出資料。

HTML 部份。

.{.{#if flash}.}.
    <div>.{.{.{ flash.message }.}.}.</div>
.{.{/if}.}.

備註:由於部落格會把花括號吃掉,因此在左右加一個點,例如「.{.{ }.}.」。

app.js 部份。

提交表單後,設定 flash 訊息。如果存在 flash 訊息,則列印在畫面上,然後刪除。

app.post('/newsletter', function(req, res) {
  var name = req.body.name || '',
    email = req.body.email;

  req.session.flash = {
    type: 'success',
    message: 'You have been signed up for the newsletter',
  };

  return res.redirect(303, '/thankyou');
});

index.js 部份。

取得 thankyou page 時列印 flash 訊息在畫面上。

// get thankyou page
router.get('/thankyou', function(req, res) {
  res.locals.flash = req.session.flash;
  res.render('thankyou', { title: 'thankyou' });
});

Demo。

Node - Cookie and Session


這篇文章的原始位置在這裡-Node - Cookie and Session

由於部落格搬遷至此,因此在這裡放了一份,以便閱讀;部份文章片段也做了些許修改,以期提供更好的內容。

node.js express