断开连接事件时有时会丢失会话数据

twh00eeo  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(146)

我正在开发一个小工具,用户可以上传他们的文件进行编辑。
服务器设置: node.js , express , express-session , connect-redis , socket.io .
由于文件占用大量空间,我提出了一个解决方案来防止遗留文件,解决方案是 socket.io ,当用户以任何方式离开时,我用 on('disconnect'... 我可以删除他上传的文件。
我遇到的问题是,在10次尝试中,有4次尝试时,会话数据显示为空 disconnect 事件被触发。
相关代码:

// index.js
let sessionMiddleware = session({
    store: new RedisStore({ client: redisClient, ttl: config.ttl }),
    secret: config.secret,
    saveUninitialized: true,
    resave: false,
    proxy: true,
    cookie: { secure: true },
});

app.set("trust proxy", 1);

io.use((socket, next) => {
    sessionMiddleware(socket.request, socket.request.res || {}, next);
});

app.use(sessionMiddleware);

// web route
const storage = multer.diskStorage({
    filename: (req, file, cb) => {
        req.session.file = {
            name,
            ext,
        };
        console.log("STORAGE route accessed", req.sessionID, req.session);
    },
});
const handleUpload = multer({ storage: storage });

const upload = (req, res, next) => {
    console.log("UPLOAD route accessed", req.sessionID, req.session);
};

router.post("/upload", handleUpload.array("files"), upload);

// socket
socket.on("disconnect", () => {
    const { sessionID } = socket.request;
    const { file } = socket.request.session;

    console.log("disconnect happened", sessionID, socket.request.session);
    console.log("disconnect file is", file);

    if (!file) {
        console.log("file doesnt exist");
        return false;
    }

    console.log("file exists and unlinking it");
});

最后,我在完全相同的条件下进行了所有测试,打开应用程序,等待1分钟,上传文件,服务器确认文件上传后,等待1分钟,关闭选项卡。
可能的结果:

disconnect happened CG-JDFffeJa0BGFyZauXw5016KTf7I0U Session {
    cookie: {
        path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: true,
        secure: true
    }
}
disconnect file is undefined
file doesnt exist

disconnect happened CG-JDFffeJa0BGFyZauXw5016KTf7I0U Session {
    cookie: {
        path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: true,
        secure: true
    },
    file: { name: 'module-bt5', ext: '.dat' }
}
disconnect file is { name: 'module-bt5', ext: '.dat' }
file exists and unlinking it

乍一看,行为是随机的,有时有效,有时无效。我错过了什么来避免它?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题