Koa2學習(七)使用cookie
Koa2 的 ctx
上下文對象直接提供了cookie的操作方法set
和get
ctx.cookies.set(name, value, [options])
在上下文中寫入cookie
ctx.cookies.get(name, [options])
讀取上下文請求中的cookie
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx, next) => {
if (ctx.url === '/set/cookie') {
ctx.cookies.set('cid', 'hello world', {
domain: 'localhost', // 寫cookie所在的域名
path: '/', // 寫cookie所在的路徑
maxAge: 2 * 60 * 60 * 1000, // cookie有效時長
expires: new Date('2018-02-08'), // cookie失效時間
httpOnly: false, // 是否只用於http請求中獲取
overwrite: false // 是否允許重寫
})
ctx.body = 'set cookie success'
}
await next()
})
app.use(async ctx => {
if (ctx.url === '/get/cookie') {
ctx.body = ctx.cookies.get('cid')
}
})
app.listen(8000)
module.exports = app
我們先訪問localhost:8000/set/cookie:
set cookie success
瀏覽器 F12打開控制台
-> application
-> cookies
-> http://localhost:8000
可以看到
cookie已經設置成功。
hello world
成功獲取到cookie。