cookie 默认配置如下:

  1. export default {
  2. domain: '',
  3. path: '/',
  4. httponly: false, //是否 http only
  5. secure: false,
  6. timeout: 0 //有效时间,0 为浏览器进程,单位为秒
  7. };

默认 cookie 是随着浏览器进程关闭而失效,可以在配置文件 src/common/config/cookie.js 中进行修改。如:

  1. export default {
  2. timeout: 7 * 24 * 3600 //将 cookie 有效时间设置为 7 天
  3. };

controller 或者 logic 中,可以通过 this.cookie 方法来获取。如:

  1. export default class extends think.controller.base {
  2. indexAction(){
  3. let cookie = this.cookie('theme'); //获取名为 theme 的 cookie
  4. }
  5. }

http 对象里也提供了 cookie 方法来获取 cookie。如:

  1. let cookie = http.cookie('theme');

controller 或者 logic 中,可以通过 this.cookie 方法来设置。如:

  1. export default class extends think.controller.base {
  2. indexAction(){
  3. this.cookie('theme', 'default'); //将 cookie theme 值设置为 default
  4. }
  5. }

http 对象里也提供了 cookie 方法来设置 cookie。如:

  1. http.cookie('theme', 'default');

如果设置 cookie 时想修改一些参数,可以通过第三个参数来控制,如:

  1. export default class extends think.controller.base {
  2. indexAction(){
  3. this.cookie('theme', 'default', {
  4. timeout: 7 * 24 * 3600 //设置 cookie 有效期为 7 天
  5. }); //将 cookie theme 值设置为 default
  6. }
  7. }

controller 或者 logic 中,可以通过 this.cookie 方法来删除。如:

  1. export default class extends think.controller.base {
  2. indexAction(){
  3. this.cookie('theme', null); //删除名为 theme 的 cookie
  4. }
  5. }

http 对象里也提供了 cookie 方法来删除 cookie。如:

  1. http.cookie('theme', null);

原文: https://thinkjs.org/zh-cn/doc/2.1/cookie.html