6. koa2 存取cookie

2019-02-06  本文已影响0人  我的昵称好听吗

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

options 参数详解

通过 options 设置 cookie name 的 value :

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);
上一篇 下一篇

猜你喜欢

热点阅读