koa2框架不提供session的處理方法,這裏咱們須要藉助一個第三方中間件koa-session
來處理session。
先安裝插件:javascript
$ npm i koa-session
經過註冊這個中間件,咱們能夠直接經過ctx.session
來操做session:java
const Koa = require('koa') const app = new Koa() const session = require('koa-session') app.keys = ['secret'] // session加密字段 app.use(session({ key: 'koa:sess', //cookie key (default is koa:sess) maxAge: 86400000, // cookie的過時時間 maxAge in ms (default is 1 days) overwrite: true, //是否能夠overwrite (默認default true) httpOnly: true, //cookie是否只有服務器端能夠訪問 httpOnly or not (default true) signed: true, //簽名默認true rolling: false, //在每次請求時強行設置cookie,這將重置cookie過時時間(默認:false) renew: false, //(boolean) renew session when session is nearly expired, }, app)) app.use(ctx => { // ignore favicon if (ctx.path === '/favicon.ico') return console.log(ctx.session) let n = ctx.session.views || 0 ctx.session.views = ++n ctx.body = n + ' views' }); app.listen(8000) module.exports = app
如今咱們來模擬一個簡單的登錄:redis
const Koa = require('koa') const app = new Koa() const session = require('koa-session') app.keys = ['secret'] // session加密字段 app.use(session({}, app)) app.use(async (ctx, next) => { if (ctx.url === '/login') { ctx.session.user_name = 'zhangsan' ctx.body = { msg: '登陸成功' } } await next() }) app.use(async (ctx, next) => { if (ctx.url === '/logout') { ctx.session = null ctx.body = { msg: '退出成功' } } await next() }) app.use(async ctx => { console.log(ctx.session) if (ctx.url === '/index') { if (ctx.session.user_name === 'zhangsan') { ctx.body = { msg: '成功匹配到用戶zhangsan' } } else { ctx.body = { msg: '登錄驗證失敗' } } } }) app.listen(8000) module.exports = app