我正在使用node.js和Typescript为网站编写后端。我最近实现了一些会话,在其中存储用户数据和他们在网站上选择的语言以备将来使用。但是,当用户重新加载页面或访问我网站的另一部分时,会话数据将刷新,我试图更改初始化会话的部分,并编辑将用户数据填充到会话中的函数。问题是我的populateuserdata文件一直运行,即使userdata已经存在,我也无法弄清楚为什么这样做。
const apiRouter = require("./routes/routes");
const session = require ("express-session");
const RedisStore = require("connect-redis")(session);
app.use(session({
store: new RedisStore(),
secret: "test",
cookie: { maxAge: 24 * 60 * 60 * 1000 }, // 1 day
resave: true,
autoreconnect: true,
saveUninitialized: true,
}));
app.use(morgan("dev"));
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.set("port", 3000);
app.set("views", path.join(__dirname, "../views"));
app.set("view engine", "pug");
app.use(require("./services/populateUserData"));
app.get("/", homeController.index);
app.use("/", apiRouter);
app.use(expressValidator);
app.use(flash);
app.use(lusca.xframe("SAMEORIGIN"));
app.use(lusca.xssProtection);
我的populateuserdata文件是这样的:
import { Request, Response, NextFunction } from "express";
const authService = require("./authService");
module.exports = (req: Request, res: Response, next: NextFunction) => {
if (!req.session.userData) {
req.session.userData = authService.getUserData(req.headers);
req.session.userData.uid = req.headers["shib-uid"];
req.session.userData.ip = req.headers["x-forwarded-for"] || (req.connection && req.connection.remoteAddress) || "";
next();
}
else {
next();
}
};
所以我想是,当数据已经存在时,populateuserdata文件中的if语句将阻止会话覆盖用户数据,我会丢失一些东西吗?
非常感谢!
/ V