Egg.js 中 Cookie 的使用


1Cookie 簡介

HTTP 是無狀態協議。簡單地說,當你瀏覽了一個頁面,然后轉到同一個網站的另一個頁 面,服務器無法認識到這是同一個瀏覽器在訪問同一個網站。每一次的訪問,都是沒有任何 關系的。

2Egg.js Cookie 的設置和獲取

 

Cookie 設置語法: ctx.cookies.set(key, value, options)

如:

this.ctx.cookies.set('name','zhangsan');

Cookie 獲取語法:ctx.cookies.get(key, options)

如:

his.ctx.cookies.get('name')

清除cookie

this.ctx.cookies.set('name',null);
或者設置 maxAge 過期時間為 0

3Egg.js Cookie 參數 options

 

https://eggjs.org/en/core/cookie-and-session.html#container

 

設置 cookie 建議的寫法:

 

      this.ctx.cookies.set('key','value',{
          maxAge:1000*3600*24,  //cookie存儲一天     設置過期時間后關閉瀏覽器重新打開cookie還存在
          httpOnly:true,
          signed:true,     //對cookie進行簽名  防止用戶修改cookie
          encrypt:true   //是否對cookie進行加密     如果cookie加密那么獲取的時候要對cookie進行解密

      });

 

ctx.cookies.get('key', { encrypt: true
});

4Egg.js 中設置中文 Cookie

 

      //如果cookie加密以后就可以設置中文cookie   (encrypt:true)
      this.ctx.cookies.set("userinfo",'張三',{
          maxAge:1000*3600*24,  //cookie存儲一天     設置過期時間后關閉瀏覽器重新打開cookie還存在
          httpOnly:true,
          signed:true,     //對cookie進行簽名  防止用戶修改cookie
          encrypt:true   //是否對cookie進行加密     如果cookie加密那么獲取的時候要對cookie進行解密
      })

 

 

 

demo:

home.js控制器

'use strict';

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

class HomeController extends Controller {
  async index() {    

      /*
      cookie:

        1.可以實現 同一個瀏覽器訪問同一個域的時候 不同頁面之間的數據共享


        2、實現數據的持久化  (關閉瀏覽器重新打開以后數據還存在)


      */

      /*
      
      第一個參數:cookies的名稱

      第二個參數:cookies的值

      第三個參數:配置

      默認情況:cookies當瀏覽器關閉以后就銷毀了
      */

      //  this.ctx.cookies.set('username','zhangsan');
 
      //注意:默認情況下面 egg.js里面的cookie沒法設置中文    argument value is invalid (code: ERR_ASSERTION)

      // this.ctx.cookies.set('username','張三');
      this.ctx.cookies.set('key','value',{
          maxAge:1000*3600*24,  //cookie存儲一天     設置過期時間后關閉瀏覽器重新打開cookie還存在
          httpOnly:true,
          signed:true,     //對cookie進行簽名  防止用戶修改cookie
          encrypt:true   //是否對cookie進行加密     如果cookie加密那么獲取的時候要對cookie進行解密

      });
      // //如果cookie加密以后就可以設置中文cookie   (encrypt:true)
      // this.ctx.cookies.set("userinfo",'張三',{
      //     maxAge:1000*3600*24,  //cookie存儲一天     設置過期時間后關閉瀏覽器重新打開cookie還存在
      //     httpOnly:true,
      //     signed:true,     //對cookie進行簽名  防止用戶修改cookie
      //     encrypt:true   //是否對cookie進行加密     如果cookie加密那么獲取的時候要對cookie進行解密
      // })

     //cookies里面設置對象         JSON.stringify()          JSON.parse()
       await this.ctx.render('home');
  } 
}

module.exports = HomeController;

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM