我正在用 Session 試驗 NodeJs。我遵循了許多網站的代碼。我想提到的最簡單的是 使用 Redis 進行會話管理的示例 NodeJS 代碼
其他論壇發現與它類似。我面臨的問題是,當我不使用 redis 作為會話存盤時,一切正常。下面是從 redis 會話切換到記憶體會話的代碼更改。
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 會話存盤的代碼是
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
}
}));
uj5u.com熱心網友回復:
經過大量閱讀,我在 npmjs 網站上得到了答案。 用于 redis-connect 包的 npmjs 站點
在版本 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
}
}));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442658.html