Koa2学习(七)使用cookie

Koa2学习(七)使用cookie

Koa2 的 ctx 上下文对象直接提供了cookie的操作方法setget
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已经设置成功。

再访问localhost:8000/get/cookie

hello world

成功获取到cookie。

猜你喜欢

转载自www.cnblogs.com/shenshangzz/p/9973407.html