我使用Redis作为会话存储,我还想使用express-session
创建自定义会话ID。到目前为止,我实现了创建具有常量字符串的会话,如下所示:
redis configuration
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var session = require('express-session');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
var client = redis.createClient();
// compress all requests
app.use(compression())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'SECRET',
resave: false,
saveUninitialized: false,
store: new RedisStore({ host: 'localhost', port: 6379, client: client}),
cookie: {
maxAge: 60000
},
genid: function(req) {
return "myApiKey";
}
}));
app.use('/', routes);
app.use('/request_api', api);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
在redis中创建键,如下所示:
127.0.0.1:6379> keys *
1) "sess:myApiKey"
但是,我无法使用此处session-store github中提及的uuid
生成唯一ID。
我已尝试在我的索引路由文件(routes/index.js
)中插入会话值,如此
/* GET home page. */
router.get('/', function(req, res, next) {
req.session.user = "12345";
res.render('index', { title: 'MyApp' });
});
但由于值genid
,无法读取undefined
函数内的值。
所以,我的问题是:
我可以使用uuid
等任何模型的user->uuid
生成会话ID吗?如果是,我该怎么做?
谢谢,任何帮助都将不胜感激。
答案 0 :(得分:1)
你可以这样做。
var crypto = require('crypto');
var uuid = require('node-uuid');
您需要node-uuid然后再使用genid函数
genid:function(req){
return uuid.v1();
},
或避免id碰撞
genid:function(req){
return crypto.createHash('sha256').update(uuid.v1()).update(crypto.randomBytes(256)).digest("hex");
},
您可以req.sessionID