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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM