快速会话无法保持会话

express-session failed to persist session

我遇到了一个棘手的问题,在 Nodejs Express 网络应用程序中,Express-session 中间无法保留 reference 类型跨多个会话的对象,同时适用于 primitive 类型值。

假设我有以下代码块: cachedFunc(引用类型)在会话中始终未定义,但 cachedText(原始类型)保留值。

我还试过深拷贝cacheFun,还是无法持久化

感谢帮助!

const _ = require("lodash");
const express = require("express");
const sessionMiddleWare = require("express-session");
const app = express();

app.use(
  sessionMiddleWare({
    name: "dzbSessionId",
    secret: "keyboard cat",
    cookie: { maxAge: 66660000 },
    resave: false,
    saveUninitialized: true
  })
);


app.get("/exam",  (req, res, next) => {
  console.info(req.session.cachedText);/*Primitive Types can be persistent */
  if (!req.session.cachedFunc/*always undefined here for referenced value*/) {
    try {
      req.session.cachedFunc = function(){};
      /*even the copied one still can't work*/
      //req.session.cachedFunc = _.cloneDeep(function(){});
      req.session.cachedText += "freeText";
    } catch (e) {}
  }
  }

此问题已解决,这是由于 函数 不是 JSON 规范的有效部分,因此 JSON.parse 和 JSON.stringify将处理它。