2017-11-25 241 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