gpt4 book ai didi

node.js - 使用 Redis 作为 session 存储的 NodeJs 抛出异常

转载 作者:行者123 更新时间:2023-12-05 09:28:30 25 4
gpt4 key购买 nike

我正在尝试使用带有 Session 的 NodeJs。我关注了许多网站的代码。我想提到的最简单的一个是 Sample NodeJS Code for session management with Redis

其他论坛发现类似的。我面临的问题是当我不使用 redis 作为 session 存储时一切正常。下面更改了从 Redis session 切换到内存 session 的代码。

app.use(session({
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}))

但是当我将 Redis 存储放回样本时,我开始遇到异常Client is closed。启用 Redis session 存储的代码是

const RedisStore = connectRedis(session)
//Configure redis client
const redisClient = redis.createClient({
host: 'localhost',
port: 6379
})
redisClient.on('error', function (err) {
console.log('Could not establish a connection with redis. ' + err);
});
redisClient.on('connect', function (err) {
console.log('Connected to redis successfully');
});
//Configure session middleware
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}));

最佳答案

经过大量阅读,我在 npmjs 站点得到了答案。 npmjs site for redis-connect package

在版本 4 之后,需要对代码进行少量更改。需要启用“传统模式”并且需要在代码中进行显式“连接”调用。

更改后的工作代码如下。添加了更改的注释。

const RedisStore = connectRedis(session)
//Configure redis client
const redisClient = redis.createClient({
host: 'localhost',
port: 6379,
legacyMode:true //********New Addition - set legacy mode to true.*******
})
redisClient.on('error', function (err) {
console.log('Could not establish a connection with redis. ' + err);
});
redisClient.on('connect', function (err) {
console.log('Connected to redis successfully');
});
redisClient.connect(); //******** New Addition - Explicite connect call *********
//Configure session middleware
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}));

关于node.js - 使用 Redis 作为 session 存储的 NodeJs 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71287116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com