koa2设置cookie

#cookie.js 
1
const Koa=require('koa'); 2 let app = new Koa(); 3 4 app.use(async ctx=>{ 5 if(ctx.url === '/index'){ 6 ctx.cookies.set('username','lisa',{ 7 domain:'localhost', 8 path:'/index', //cookie写入的路径 9 maxAge:1000*60*60*1, 10 expires:new Date('2018-07-06'), 11 httpOnly:false, 12 overwrite:false 13 } 14 ); 15 ctx.body = 'cookies is seted;' 16 }else{ 17 console.log(ctx.cookies.get('username')) 18 if(ctx.cookies.get('username')){ 19 ctx.body = 'welcome ' + ctx.cookies.get('username'); 20 }else{ 21 22 ctx.body = 'hello koa2' 23 } 24 } 25 }); 26 27 app.listen(3333, ()=>{ 28 console.log('set cookie') 29 })

运行:node cookie.js

浏览器中访问 http://localhost:3333/index  ,可查看到cookie已经设置成功。

 

再访问https://localhost:3333/index/user  , 可获取设置的cookie

猜你喜欢

转载自www.cnblogs.com/brand-code/p/9274823.html