美文网首页
把koa2 的session存储到MongoDB

把koa2 的session存储到MongoDB

作者: Justcool | 来源:发表于2017-12-11 15:32 被阅读107次

    需要用到中间件

    koa-session-minimal,提供koa2中session的读写接口

    koa-session-mongoose,提供mongoose数据库中session数据的读写操作

    示例代码

    
    const Koa = require('koa');
    
    const mongoose = require('mongoose');
    
    const session = require('koa-session-minimal');
    
    const MongooseStore = require('koa-session-mongoose');
    
    const app = new Koa();
    
    mongoose.connect('mongodb://localhost:27017/test',{useMongoClient:true});
    
    app.use(session({
    
    store: new MongooseStore()
    
    }));
    
    app.use(async ctx => {
    
    const { session } = ctx;
    
    let n = session.views || 0;
    
    session.views = ++n;
    
    ctx.body = `${n} view(s)`;
    
    });
    
    app.listen(3000)
    
    console.log('session is starting at port 3000');
    
    

    相关文章

      网友评论

          本文标题:把koa2 的session存储到MongoDB

          本文链接:https://www.haomeiwen.com/subject/oniiixtx.html