ThinkJS Cookie

2021-09-17 14:26 更新

Cookie

獲取 cookie

controller 或者 logic 中,可以通過 this.cookie 方法來獲取。如:

export default class extends think.controller.base {
  indexAction(){
    let cookie = this.cookie("theme"); //獲取名為 theme 的 cookie
  }
}

http 對象里也提供了 cookie 方法來獲取 cookie。如:

let cookie = http.cookie("theme");

cookie 配置

cookie 默認(rèn)配置如下:

export default {
  domain: "", 
  path: "/",
  httponly: false, //是否 http only
  secure: false,
  timeout: 0  //有效時(shí)間,0 為瀏覽器進(jìn)程,單位為秒
};

默認(rèn) cookie 是隨著瀏覽器進(jìn)程關(guān)閉而失效,可以在配置文件 src/common/config/cookie.js 中進(jìn)行修改。如:

export default {
  timeout: 7 * 24 * 3600  //將 cookie 有效時(shí)間設(shè)置為 7 天
};

設(shè)置 cookie

controller 或者 logic 中,可以通過 this.cookie 方法來設(shè)置。如:

export default class extends think.controller.base {
  indexAction(){
    this.cookie("theme", "default"); //將 cookie theme 值設(shè)置為 default
  }
}

http 對象里也提供了 cookie 方法來設(shè)置 cookie。如:

http.cookie("theme", "default");

如果設(shè)置 cookie 時(shí)想修改一些參數(shù),可以通過第三個(gè)參數(shù)來控制,如:

export default class extends think.controller.base {
  indexAction(){
    this.cookie("theme", "default", {
      timeout: 7 * 24 * 3600 //設(shè)置 cookie 有效期為 7 天
    }); //將 cookie theme 值設(shè)置為 default
  }
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號