我遇到了问题。 我设置了一个会话,我创建了这个对象:
req.session.userId = user.id
但是当我重定向到另一个页面时,这个userId对象在那里是未定义的。我发现它是由重定向引起的。你知道如何在重定向后使我的req.session.userId值可用吗?
答案 0 :(得分:2)
您可以按照以下方式创建会话: -
的package.json
{
"name": "server",
"version": "0.0.0",
"description": "it is a server",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "~4.0.0",
"body-parser": "~1.0.1",
"express-session": "^1.0.2",
"connect": "^2.13.0",
"method-override": "~1.0.0"
},
"author": "SM@K",
"license": "ISC"
}
index.js
var express = require('express');
var session = require('express-session');
var MemoryStore = require('connect').session.MemoryStore
// create our app
var app = express();
app.use(session({
secret: "secret",
store: new MemoryStore({reapInterval: 60000 * 10})
}));
app.get('/', function(req, res) {
req.session.from_session = 10;
res.redirect('/session');
});
app.get('/session', function(req, res) {
res.send("Comming From Session: " + req.session.from_session);
});
app.get('/session-test', function(req, res) {
res.send("Test Session: " + req.session.from_session);
});
app.listen(3001);
console.log('listen 3001');