egg.js Cookie的使用

发布于 5 年前 作者 magege666 3895 次浏览 最后一次编辑是 5 年前 来自 分享

1、egg.js Cookie简介

● cookie 是存储于访问者的计算机中的变量。可以让我们用同一个浏览器访问同一个域名的时候共享数据。

● HTTP是无状态协议。简单地说,当你浏览了一个页面,然后转到同一个网站的另一个页面,服务器无法认识到这是同一个浏览器在访问同一个网站。每一次的访问,都是没有任何关系的。

2、Egg.js中Cookie的设置和获取

Cookie设置语法:

ctx.cookies.set(key, value, options);
this.ctx.cookies.set('name','zhangsan');

Cookie获取语法:

ctx.cookies.get(key, options)
this.ctx.cookies.get('name')

清除Cookie:

this.ctx.cookies.set('name',null);

清除Cookie也可以设置maxAge过期时间为0

3、Egg.js中Cookie参数options

https://eggjs.org/en/core/cookie-and-session.html#container

4、设置加密Cookie 以及获取加密Cookie(建议设置方法)

ctx.cookies.set(key, value, {  
maxAge:24 * 3600 * 1000,
  httpOnly: true, // by default it's true
  encrypt: true, // cookies are encrypted during network transmission
});

ctx.cookies.get('frontend-cookie', {
  encrypt: true
});

5、Egg.js中设置中文Cookie

第一种解决方案Buffer转换:

console.log(new Buffer(‘hello, world!’).toString(‘base64’)); // 转换成base64字符串:aGVsbG8sIHdvcmxkIQ== console.log(new Buffer(‘aGVsbG8sIHdvcmxkIQ==’, ‘base64’).toString()); // 还原base64字符串:hello, world!

第二种解决方案 cookie加密:

ctx.cookies.set(key, value, { maxAge:24 * 3600 * 1000, httpOnly: true, // by default it’s true encrypt: true, // cookies are encrypted during network transmission });

1 回复

设置cookie:

ctx.cookies.set(key, value, {  
maxAge:24 * 3600 * 1000,
  httpOnly: true, // by default it's true
  encrypt: true, // cookies are encrypted during network transmission
});

获取cookie

ctx.cookies.get('frontend-cookie', {
  encrypt: true
});

回到顶部