2017-11-25 8 views
0

誰かがExpressionセッションをRedisに格納するための作業コードを持っていますか?Expressセッションは、式セッション - redis接続を使用してredisに格納されていません

角度4のログインページを作成しています。 Expressセッションを使用してRedisにユーザーセッションを保存したい。

Iamの取得中にエラーセッションは、私はRedisの中にセッションIDを表示することができますどのように

が定義されていませんか?

Iamはこれを打ちました。どんな身体も同じ問題に直面していますか?助けてくれてありがとう

+0

最後の2日間からこれを試していて、得られていません。おかげです。 – Jan

答えて

1

express-sessionconnect-redisを使って実現できます。

完全な例:あなたはthisthisを読みたいかもしれません詳細については

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:*' 
*/ 

希望すると便利です。

+0

私はexpress-sessionとconnect-redisも使用しています。私はあなたのコードをredisからフェッチしようとしました、client.get(sessionKey、(err、data)=> { console.log( 'セッションデータin redis:'、data) })。しかし、それはnullを返します。それは赤目に格納されていません。セッションがどこに保存されているのかわかりません。 – Jan

+0

'client.get()'の 'err'オブジェクトは何を出力しますか? @Jan –

+0

また、 'Null'も返します。 – Jan

関連する問題