安装依赖 : express-session connect-redis redis
创建 redis 服务
const redis = require('redis')
const {REDIS_CONF} =require('../conf/db')
const redisCli = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
redisCli.on('error', err => {
console.error(err)
})
module.exports = redisCli
app.js文件中使用
const express = require('express');
const session = require('express-session')
const RedisStore = require('connect-redis')(session) // 这里直接把session传进去
const app = express();
const redisClient = require('./db/redis') // 引入之前写好得redis服务
const sessionStore = new RedisStore({
client: redisClient
})
app.use(session({
secret: 'express_Server2375#', // 类似密钥一样得东西
cookie: {
// path: '/', // 默认配置
// httpOnly: true, // 默认配置
maxAge: 24 * 60 * 60 * 1000
},
store: sessionStore
}))
// .....