我正在使用快速会话创建登录应用程序。当我通过邮寄请求登录应用程序时,将创建cookie,但Session不适合我。
Server.js
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(cookieParser());
app.use(session({
key: 'user_sid',
secret: 'somerandonstuffs',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
res.redirect('/');;
} else {
next();
}
};
app.post('/login', function (req, res) {
console.log(req.session.user)
if (req.session.user && req.cookies.user_sid) {
result = { "message": "loggedinwithsession" };
res.send(result);
} else {
var data = req.body;
var responseData = {};
console.log(data);
res.setHeader('Content-Type', 'application/json');
controller.cont.login(data.email, data.password).then(result => {
res.send(result),
req.session.user = result;
}
).catch(result => res.send(result))
}
})
答案 0 :(得分:0)
您可以在设置会话之前发送结果数据。
controller.cont.login(data.email, data.password).then(result => {
res.send(result), //wrong
req.session.user = result;
}).catch(result => res.send(result))
你应该这样做。
controller.cont.login(data.email, data.password).then(result => {
console.log("setting session"); //for debugging
req.session.user = result; // first set session
res.send(result); // then send result
}).catch(result => res.send(result))
这是最小版本。
app.all('/', function(req, res){
console.log(req.session)
res.send("welcome")
})
app.get('/set', function(req, res){
console.log(req.session)
res.setHeader('Content-Type', 'text/html');
req.session.data = "test session value"
res.send("test")
})