const Koa = require(‘koa’)
const router = require(‘koa-router’)()
const views = require(‘koa-views’)
const nunjucks = require(‘nunjucks’)
const session = require(‘koa-session’)
const app = new Koa()
app.keys = [‘123456’]
app.use(
session(
{
maxAge: 10*1000
},
app
)
)
app.use(
views(__dirname + ‘/views’, {
map: { html: ‘nunjucks’ }
})
)
//cookie
router.get(‘/’, ctx => {
ctx.cookies.set(‘user’, ‘username’)
ctx.body = ‘cookie’
})
router.get(‘/test’, ctx => {
let count = ctx.cookies.get(‘count’) //获取cookie
if (count > 0) {
count++
ctx.cookies.set(‘count’, count, {
maxAge: 2000 //设置cookie过期时间
})
} else {
count = 1
ctx.cookies.set(‘count’, count)
}
ctx.body = count
})
//session
router.get(‘/session’, async ctx => {
ctx.session.user = ‘admin’
console.log(ctx.session.user)
ctx.body = ‘set session’
})
router.get(‘/sessionq’, async ctx => {
let user = ctx.session.user
console.log(user)
ctx.body = user
})
app.use(router.routes())
app.listen(3001, () => {
console.log(‘server is running’)
})
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/282092.html