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