Express-Session自定义值无法跨Node.js API路由保存求助
Express-Session 自定义值无法跨路由保存的解决办法
核心问题1:跨域请求未携带凭证
你的CORS配置中注释掉了credentials: true,这会导致浏览器在跨域请求时,不会将后端设置的Session Cookie发送回服务器,服务器无法识别用户的Session,自然取不到自定义属性。
修改CORS配置:
app.use(cors({ origin: 'http://localhost:3000', credentials: true // 必须开启,允许跨域请求携带凭证(Cookie) }));
同时前端请求必须配合设置携带凭证:
- 若使用Axios:
axios.get('/api/getSession', { withCredentials: true }) - 若使用Fetch:
fetch('/api/getSession', { credentials: 'include' })
核心问题2:getSession路由存在未定义变量
你的getSession路由中,res.json(response);里的response变量未定义,会引发报错。需要改为返回Session中的自定义属性:
router.get(`/getSession`, async (req, res, next) => { try { console.log(req.session.custom_attr); res.json({ custom_attr: req.session.custom_attr }); // 返回实际的Session值 } catch (e) { res.status(500).json({ message: '发生意外错误', error: e.message }); } });
额外提示:Session存储机制(开发/生产环境差异)
当前你使用的是express-session默认的内存存储,这种方式仅适合开发测试,重启服务后所有Session会丢失。生产环境建议使用Redis、MongoDB等持久化存储方案,比如通过connect-redis插件对接Redis。
内容的提问来源于stack exchange,提问作者mikefreudiger
相关产品推荐
相关产品推荐

