首页 > 解决方案 > 如何使用 express-session 在会话存储表中保存其他列

问题描述

在我的 NodeJS 应用程序中,我使用 express-session 中间件将用户会话数据保存到 PostgreSQL 数据库中。我注意到,express-session 默认只在为会话存储指定的数据库表中保存 sid(字符串)、sess(json)、expire(日期时间)。

但是我在会话表中还有其他列(userId、userType 等),有没有办法将它们与用户会话一起保存。虽然我们可以将这些附加数据保存在 sess 列中,但我想保存在特定列中以获得更大的灵活性。

此外,如果我更改表的列名(将“sid”更改为“user_session_id”),则不允许我保存会话数据。这是预期的吗?有什么办法可以更改列名。

下面提供的代码片段供参考

enum SessionConfig {
    name = 'xc2id',
    tableName = 'session',
    schemaName = 'xc2',
    sessionPruneInterval = 20 //seconds
}

export const pgPool = new pg.Pool({
    host: config.DB_HOST_NAME,
    port: parseInt(config.DB_PORT),
    database: config.DB_NAME,
    user: config.DB_ADMIN_USERNAME,
    password: config.DB_ADMIN_PASSWORD,
    ssl: true
});

//Todo: cookie - secure: true
const sessionCookie = {
    secure: false,
    maxAge: parseInt(config.COOKIE_MAX_AGE)
};

const sessionStore = new pgSession({
    pool: pgPool,
    tableName: SessionConfig.tableName,
    schemaName: SessionConfig.schemaName,
    pruneSessionInterval: SessionConfig.sessionPruneInterval
});

export const sessionMiddleWare = session(
    {
        name: SessionConfig.name as string,
        genid: () => BLHelper.getRandomSHA256(),
        store: sessionStore,
        secret: config.SESSION_SECRET_CODE,
        cookie: sessionCookie,
        resave: false,
        saveUninitialized: false,
    }
);

标签: node.jspostgresqlexpress-session

解决方案


推荐阅读