我的应用程序注销功能遇到问题。
问题
调用req.session.destroy不会从仅生产中的Sessions MongoDB集合中删除会话数据。
请求到达服务器,注销方法运行,destroy函数未返回任何错误,在会话上运行console.log表示该会话为空,但在刷新页面时,该用户仍处于登录状态,并检查db.sessions。 find()显示未更改的会话数据。
我认为子域设置与此有关,因为本地可以按预期工作。我只是不知道这是什么,因为该应用程序否则功能正常。
正在使用的关键软件包
该功能在本地运行良好(API和React应用都在本地主机上运行,只是端口不同)。
已设置生产,以便
server.js-重要部分
//use sessions for tracking logins
var sessionData = {
name: 'secure_name', // for testing
secret: 'secure_secret', // for testing
resave: true,
rolling: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: {
"maxAge": (1000 * 60 * 60 * 7), // 7 days.
secure: false,
path: '/',
domain: process.env.DOMAIN
}
};
// Setup session with config and make the app use it.
var sessionMiddleware = session(sessionData);
app.use(sessionMiddleware);
...
// User - Logout.
app.get('/api/users/logout', user.logout);
user.logout方法
// Logout user.
exports.logout = (req, res, next) => {
// Only if there is an active session.
if (req.session) {
// delete session object
req.session.destroy(error => {
req.session = null;
if (error) return next(error);
res.send({ logout: true })
});
}
}
反应退出方法请求
// Logout - end this user session.
@action logout() {
// Destroy session.
return axios.get(config.url + 'api/users/logout', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
})
任何帮助将不胜感激。
答案 0 :(得分:0)
我找到了解决我问题的方法。如果有人碰巧遇到类似问题,请在此处发布。
发送到服务器的GET请求不包含任何凭据,因为默认情况下它设置为false。
解决方案是在请求中将“ with-credentials”显式设置为true,如下所示:
// Logout - end this user session.
@action logout() {
// Destroy session.
return axios.get(config.url + 'api/users/logout', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
withCredentials: true
})