Koa2 的 ctx
上下文對象直接提供了cookie的操做方法set
和get
ctx.cookies.set(name, value, [options])
在上下文中寫入cookie
ctx.cookies.get(name, [options])
讀取上下文請求中的cookiejavascript
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:java
set cookie success
瀏覽器 F12打開控制檯
-> application
-> cookies
-> http://localhost:8000
能夠看到
cookie已經設置成功。瀏覽器
再訪問localhost:8000/get/cookie:bash
hello world
成功獲取到cookie。cookie