session和cookie
作者:互联网
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') })
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') })
标签:count,app,ctx,session,cookie,user,router 来源: https://www.cnblogs.com/GFM0518/p/16622491.html