Koa2學習(七)使用cookie


Koa2學習(七)使用cookie

Koa2 的 ctx 上下文對象直接提供了cookie的操作方法setget
ctx.cookies.set(name, value, [options])在上下文中寫入cookie
ctx.cookies.get(name, [options]) 讀取上下文請求中的cookie

const Koa = require('koa')
const app = new Koa()
app.use(async(ctx, next) => {
	if (ctx.url === '/set/cookie') {
	    ctx.cookies.set('cid', 'hello world', {
	        domain: 'localhost', // 寫cookie所在的域名
	        path: '/', // 寫cookie所在的路徑
	        maxAge: 2 * 60 * 60 * 1000, // cookie有效時長
	        expires: new Date('2018-02-08'), // cookie失效時間
	        httpOnly: false, // 是否只用於http請求中獲取
	        overwrite: false // 是否允許重寫
	    })
	    ctx.body = 'set cookie success'
    }
    await next()
})
app.use(async ctx => {
	if (ctx.url === '/get/cookie') {
		ctx.body = ctx.cookies.get('cid')
	}
})

app.listen(8000)

module.exports = app

我們先訪問localhost:8000/set/cookie

set cookie success

瀏覽器 F12打開控制台 -> application -> cookies -> http://localhost:8000 可以看到

cookie已經設置成功。

再訪問localhost:8000/get/cookie

hello world

成功獲取到cookie。


免責聲明!

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



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