Koa2学习(八)使用session

Koa2学习(八)使用session

koa2框架不提供session的处理方法,这里我们需要借助一个第三方中间件koa-session来处理session。
先安装插件:

$ npm i koa-session

通过注册这个中间件,我们可以直接通过ctx.session来操作session:

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
  1. 这个ctx.session是针对某一个浏览器用户的。
  2. 不断地刷新访问浏览器,浏览器上显示的访问次数会增加。
  3. 如果不使用数据库,session是保存在内存中的。在服务端通常会使用redis等方案来使session持久化。

现在我们来模拟一个简单的登陆:

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
  1. 当用户登陆到login页面时,session会将zhangsan保存为user_name。
  2. 用户访问index页面时,session会对当前的user_name做匹配,如果匹配成功,则认证登陆成功。
  3. 用户访问logout页面是,session会自我销毁。
  4. 这样再次访问index页面时,登陆就会失败。

猜你喜欢

转载自www.cnblogs.com/shenshangzz/p/9973422.html