美文网首页
6. koa2 存取cookie

6. koa2 存取cookie

作者: 我的昵称好听吗 | 来源:发表于2019-02-06 15:59 被阅读0次

语法:
ctx.cookies.get(name, [options])
ctx.cookies.set(name, value, [options])

options 参数详解

通过 options 设置 cookie name 的 value :

  • maxAge 一个数字表示从 Date.now() 得到的毫秒数
  • signed cookie 签名值
  • expires cookie 过期的 Date (ms)
  • path cookie 路径, 默认是'/'
  • domain cookie 域名
  • secure 安全 cookie
  • httpOnly 服务器可访问 cookie, 默认是 true
  • overwrite 一个布尔值,表示是否覆盖以前设置的同名的 cookie (默认是 false). 如果是 true, 在同一个请求中设置相同名称的所有 Cookie(不管路径或域)是否在设置此Cookie 时从 Set-Cookie 标头中过滤掉。

1. 设置cookie

ctx.cookies.set('mycookie', 'hello-value');

2. 读取cookie

ctx.cookies.get('mycookie');
image.png

完整案例

/**
 * 项目入口文件
 */

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const router = new Router();
app.use(bodyParser());

// hello 
router.get('/hello', (ctx, next) => {
    ctx.cookies.set('mycookie', 'hello-value');
    ctx.body = 'hello';
});

// user
router.get('/user', (ctx, next) => {
    
    ctx.body = ctx.cookies.get('mycookie');
});
   
app.use(router.routes());
app.use(router.allowedMethods());
// 监听3000端口
app.listen(3000);

相关文章

网友评论

      本文标题:6. koa2 存取cookie

      本文链接:https://www.haomeiwen.com/subject/oocisqtx.html