在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:Secbone/koa-session2开源软件地址:https://github.com/Secbone/koa-session2开源编程语言:JavaScript 100.0%开源软件介绍:koa-session2Middleware for Koa2 to get/set session use with custom stores such as Redis or mongodb Use native ES6(async/await) by Nodejs v7.6.0 + Or you can use the old versions: Requirenode v7.6 + Install
Usageconst Koa = require("koa");
const session = require("koa-session2");
const app = new Koa();
app.use(session({
key: "SESSIONID", //default "koa:sess"
})); Custom StoresStore.js const Redis = require("ioredis");
const { Store } = require("koa-session2");
class RedisStore extends Store {
constructor() {
super();
this.redis = new Redis();
}
async get(sid, ctx) {
let data = await this.redis.get(`SESSION:${sid}`);
return JSON.parse(data);
}
async set(session, { sid = this.getID(24), maxAge = 1000000 } = {}, ctx) {
try {
// Use redis set EX to automatically drop expired sessions
await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000);
} catch (e) {}
return sid;
}
async destroy(sid, ctx) {
return await this.redis.del(`SESSION:${sid}`);
}
}
module.exports = RedisStore; main.js const Koa = require("koa");
const session = require("koa-session2");
const Store = require("./Store.js");
const app = new Koa();
app.use(session({
store: new Store()
}));
app.use(ctx => {
let user = ctx.session.user;
ctx.session.view = "index";
});
app.use(ctx => {
// refresh session if set maxAge
ctx.session.refresh()
}) OptionsMost options based on cookies
Methods
LicenseMIT |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论