【问题标题】:Express Session is not storing in redis using Expression session - connect redisExpress Session 未使用 Expression 会话存储在 redis 中 - 连接 redis
【发布时间】:2017-11-26 08:04:48
【问题描述】:

有人有在 Redis 中存储 Expression 会话的工作代码吗?

我正在创建 Angular 4 登录页面。我想使用 Express 会话将用户会话存储在 Redis 中。

我收到错误会话未定义

如何在 Redis 中查看 sessionID?

我对此感到震惊。有没有人面临同样的问题?感谢您的帮助

【问题讨论】:

  • 我从过去 2 天开始尝试这个但没有得到。谢谢你的帮助

标签: javascript node.js express redis router


【解决方案1】:

您可以使用express-sessionconnect-redis 来实现它。

一个完整的例子:

const express = require('express');
const app = express();

const session = require('express-session');
const RedisStore = require('connect-redis')(session);

// Create redis client
const redis = require('redis');
// default client tries to get 127.0.0.1:6379
// (a redis instance should be running there)
const client = redis.createClient();
client.on('error', function (err) {
  console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
  console.log('connected to redis successfully');
});

// Initialize middleware passing your client
// you can specify the way you save the sessions here
app.use(session({
  store: new RedisStore({client: client}),
  secret: 'some secret',
  resave: false,
  saveUninitialized: true
}));

app.get('/', (req, res) => {
  // that's how you get the session id from each request
  console.log('session id:', req.session.id)
  // the session will be automatically stored in Redis with the key prefix 'sess:'
  const sessionKey = `sess:${req.session.id}`;
  // let's see what is in there
  client.get(sessionKey, (err, data) => {
    console.log('session data in redis:', data)
  })
  res.status(200).send('OK');
})

app.listen(3000, () => {
  console.log('server running on port 3000')
})

/*
If you check your redis server with redis-cli, you will see that the entries are being added:
$ redis-cli --scan --pattern 'sess:*'
*/

有关更多信息,您可能需要阅读 thisthis

希望这会有所帮助!

【讨论】:

  • 我也在使用 express-session 和 connect-redis。我试过你的代码从 redis 获取 client.get(sessionKey, (err, data) => { console.log('session data in redis:', data) }) 。但它返回 null 。它不存储在redis中。我不确定会话存储在哪里。
  • 来自client.get()err 对象输出什么? @简
  • 错误也返回“Null”。
  • 你可以看到控制台日志connected to redis successfully?你可以在命令行中使用redis-cli 访问你本地的redis 实例吗?
  • 是的,Redis 正在连接并且能够从命令行访问 redis 实例。
猜你喜欢
  • 2018-12-16
  • 2012-04-28
  • 2016-09-07
  • 2013-12-13
  • 1970-01-01
  • 2012-08-15
  • 2016-06-15
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多