koa中使用cookie

Cookie:

① cookie 是存储于访问者的计算机中的变量。可以让我们用同一个浏览器访问同一个域的不同页面的时候共享数据。
② HTTP 是无状态协议。简单地说,当你浏览了一个页面,然后转到同一个网站的另一个页面,服务器无法认识到这是同一个浏览器在访问同一个网站。每一次的访问,都是没有任何关系的。
③ 作用:

    1、保存用户信息(如浏览不同页面保存登录状态,购物车信息等)
    2、浏览器历史记录
    3、猜你喜欢的功能
    4、10天免登陆
    5、多个页面之间的数据传递
    6、cookie实现购物车功能
 

Koa 中使用Cookie:

① 设置 cookie:ctx.cookies.set(name, value, [options])

  通过options 设置cookie name 的value :

  

② 获取 cookie 的值: ctx.cookies.get('name');

 

maxAge:设置cookie的过期时间

const Koa = require('koa')
const views = require('koa-views')
const app = new Koa()
const router = require('koa-router')()
const render = require('koa-art-template')
const path = require('path')

//配置 koa-art-template模板引擎
render(app, {
    root: path.join(__dirname, 'views'),   // 视图的位置
    extname: '.html',  // 后缀名
    debug: process.env.NODE_ENV !== 'production'  //是否开启调试模式

});

router.get('/login',async (ctx)=>{
    ctx.cookies.set('userName','jack',{
        maxAge:60*60*1000 //cookie过期时间:1h后
    })
    await ctx.render('login')
})

router.get('/', async (ctx) => {
    let userName = ctx.cookies.get('userName')
    console.log('首页获得userName:',userName)
    await ctx.render('index')
})

router.get('/list', async (ctx) => {
    let userName = ctx.cookies.get('userName')
    console.log('列表获得userName:', userName)
    await ctx.render('list')
})

app.use(router.routes()); 
app.use(router.allowedMethods());
app.listen(3000);

  第一次进入 首页,获取到的 userName = undefined,进入登录页,才会在 cookie 中设置 userName

  

   再次进入 列表页和 首页,就会获取 cookie 中的 userName 了:

  

  这里设置了1h后过期,1h 内进入这个域的不同页面都可以获取 cookie 的值,到期后不能获取。可以通过设置过期时间测试一下 maxAge 这个参数

httpOnly,true表示这个cookie只有服务器端可以访问,false表示客户端(js),服务器端都可以访问,默认是true

 设置为 false,访问登录页后,设置了cookie,再返回首页,客户端和服务端都可以打印出 cookie 值:(客户端通过 document.cookie 可以获取)

设置为 true 后,只有服务端能获取,客户端获取不到cookie的值:

path:配置可以访问的页面,默认是 / ,所有页面

 这里配置只有 list 页面可以访问 cookie

 

domain , 正常情况下不用设置 , 默认就是当前域下面的所有页面都可以访问
若 设置为 domain : .baiducom , 则表示 a.baidu.com 和 b.baidu.com 等 可以访问 cookie
 
当设置 cookie 的 value 值为中文时,会不合法,解决方法是将中文转换成 base64 编码:
即:

 

 

 

posted @ 2021-01-30 19:04  shanlu  阅读(539)  评论(0编辑  收藏  举报