# Cookie
[TOC=2,3]
## 獲取 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 默認配置如下:
~~~
export default {
domain: "",
path: "/",
httponly: false, //是否 http only
secure: false,
timeout: 0 //有效時間,0 為瀏覽器進程,單位為秒
};
~~~
默認 cookie 是隨著瀏覽器進程關閉而失效,可以在配置文件?`src/common/config/cookie.js`?中進行修改。如:
~~~
export default {
timeout: 7 * 24 * 3600 //將 cookie 有效時間設置為 7 天
};
~~~
## 設置 cookie
controller 或者 logic 中,可以通過?`this.cookie`?方法來設置。如:
~~~
export default class extends think.controller.base {
indexAction(){
this.cookie("theme", "default"); //將 cookie theme 值設置為 default
}
}
~~~
http 對象里也提供了?`cookie`?方法來設置 cookie。如:
~~~
http.cookie("theme", "default");
~~~
如果設置 cookie 時想修改一些參數,可以通過第三個參數來控制,如:
~~~
export default class extends think.controller.base {
indexAction(){
this.cookie("theme", "default", {
timeout: 7 * 24 * 3600 //設置 cookie 有效期為 7 天
}); //將 cookie theme 值設置為 default
}
}
~~~
- 快速入門
- 介紹
- 創建項目
- 項目結構
- 代碼規范
- 升級指南
- 進階應用
- 模塊
- 控制器
- 視圖
- 配置
- 路由
- 模型
- 介紹
- 事務
- 關聯模型
- Mysql
- MongoDB
- SQLite
- Adapter
- 介紹
- Cache
- Session
- WebSocket
- Template
- 擴展功能
- thinkjs 命令
- 靜態資源訪問
- Middleware
- Service
- Cookie
- 錯誤處理
- 錯誤信息
- 數據校驗
- 國際化
- 路徑常量
- REST API
- 定時任務
- 線上部署
- 推薦模塊
- API
- think
- think.base
- think.http.base
- http
- controller
- rest controller
- model
- model.mongo
- middleware