【问题标题】:Express session data is not removed from Mongo store when destroy is invoked in Production在生产中调用销毁时,不会从 Mongo 存储中删除 Express 会话数据
【发布时间】:2019-07-04 03:38:56
【问题描述】:

我的应用程序的注销功能遇到问题。

问题

调用 req.session.destroy 不会从 Production only 中的 Sessions MongoDB 集合中删除会话数据。

请求到达服务器,logout 方法运行,destroy 函数没有返回错误,在 session 上运行 console.log 显示它是空的,但在页面刷新时用户仍然登录,并检查 db.sessions。 find() 显示未触及的会话数据。

我认为子域设置与此有关,因为本地工作正常。我只是无法弄清楚这是什么,因为该应用程序运行正常。

正在使用的关键包

  • 快速会话
  • 连接-mongo
  • cors

该功能在本地运行良好(API 和 React 应用程序都在 localhost 上运行,只是端口不同)。

生产是这样设置的

  • api.mydomain.com 是带有 Express API 和 Mongo db 的 Node 服务器。
  • app.mydomain.com 是一个向 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 })
        });
    }
}

React 注销方法请求

        // 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',
                },
            })

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js mongodb express express-session


    【解决方案1】:

    我找到了解决问题的方法。在这里发帖以防其他人偶然发现类似问题。

    发送到服务器的 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
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多