1. 程式人生 > >egg學習筆記(5)--cookie,session

egg學習筆記(5)--cookie,session

簡介

  1. session 是另一種記錄客戶狀態的機制,不同的是 Cookie 儲存在客戶端瀏覽器中,而

session 儲存在伺服器上。

  1. 當瀏覽器訪問伺服器併發送第一次請求時,伺服器端會建立一個 session 物件,生成一

個類似於 key,value 的鍵值對, 然後將 key(cookie)返回到瀏覽器(客戶)端,瀏覽器下次再訪問時,攜帶 key(cookie),找到對應的 session(value)

目錄結構

clipboard.png

cookie

setcookie

//router.js

  router.get('/setcookie', controller.cookie.setcookie);
  router.get('/getcookie', controller.cookie.getcookie);
  router.get('/clearcookie', controller.cookie.clearcookie);

//controller/cookie.js

'use strict';

const Controller = require('egg').Controller;

class CookieController extends Controller {
    async setcookie() {
        this.ctx.cookies.set("name", "張三",{
            maxAge: 24 * 3600 * 1000,
            httpOnly: true, // by default it's true
            encrypt: true, // 加密,並且可以設定為中文
        });
        await this.ctx.render('setcookie')
    }
    async getcookie() {
        let name = this.ctx.cookies.get("name",{
            encrypt: true, 
        });
        await this.ctx.render('getcookie', {
            name
        })
    }
    async clearcookie() {
        // this.ctx.cookies.set("name", null);
        this.ctx.cookies.set("name", {
            maxAge: 0,
        });
        this.ctx.redirect("/")
    }
}

module.exports = CookieController;

//getcookie.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
            <%= name %>
    </div>
    
</body>
</html>

clipboard.png

session

//router.js

  router.get('/setsession', controller.session.setsession);
  router.get('/getsession', controller.session.getsession);

//congif/config.default.js

  config.session = {
    key:'SESSION_ID',  //key名字
    maxAge:1000*60*24,
    httpOnly:true,
    encrypt:true, //加密 
    renew:true //最大時間範圍內,重新整理,自動增加最大時間
  }

//controller/session.js

'use strict';

const Controller = require('egg').Controller;

class SessionController extends Controller {
    async setsession() {
        this.ctx.session.userinfo = {
            name: '張三',
            age: '20'
        }
        await this.ctx.render('setsession')
    }
    async getsession(){
        var userinfo=this.ctx.session.userinfo;
        await this.ctx.render('getsession',{
            userinfo
        })
    }
}

module.exports = SessionController;

clipboard.png