2017-11-25 242 views
0

任何人都有在Redis中存储表达式会话的工作代码吗?快速会话不使用表达式会话存储在redis中 - 连接redis

Iam创建角度4登录页面。我想通过使用Express会话在Redis中存储用户会话。

荫收到错误会话未定义

我如何可以查看Redis的的SessionID?

Iam打了这个。任何机构是否面临同样的问题?感谢您的帮助

+0

Iam从最近2天开始尝试,并没有得到。感谢您的帮助 – Jan

回答

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

希望这会有所帮助!

+0

我也在使用express-session和connect-redis。我尝试了从redis,client.get(sessionKey,(err,data)=> {console.log('redis中的会话数据:',data) })中获取您的代码。但它返回null。它不存储在redis中。我不确定会话存储在哪里。 – Jan

+0

client.get()输出的'err'对象是什么? @Jan –

+0

错误也会返回'Null' – Jan