首页 > 解决方案 > 我可以获取“req.session”(快速会话)数据吗?

问题描述

app.get("/route1", async (req, res) => {
  res.header('Access-Control-Allow-Origin', '*');
  console.log('TCL: req.session', req.session);
  res.send(req.session);
});

app.get("/route2", (req, res) => {
  req.session.test = "test";
  console.log('TCL: req.session', req.session);
  res.send(req.session);
});

route2 设置会话数据,我的终端/浏览器记录它就好了。如果我在浏览器 url 栏中访问 route1,则数据会成功显示在浏览器和终端中

如果我尝试在 react 组件中获取 route2,我不会获得存储在 req.session.test 中的数据,并且我的终端只记录其中的 cookie 部分,如下所示:

TCL: req.session Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: false,
     secure: false } }

配置:

app.use(session({
    secret: prodkeys.sessionSecret,
    resave: false,
    saveUninitialized: false,
    cookie: {
        httpOnly: false,
        secure: false,
      }
}));

在组件中:

const isSession = await axios.get("http://localhost:5001/route1",
   {credentials: 'include', proxy: true});

标签: javascriptreactjsexpressfetchexpress-session

解决方案


我不是 100% 修复了哪个部分,但我安装了 cors 并以这种方式配置了我的 fetch 并解决了它:

const isSession = await axios.get("http://localhost:5001/route1",
    {credentials: 'include', proxy: true, withCredentials: true});

索引.js:

app.use(cors({
    origin: ['*'],
    methods: ['GET','POST'],
    credentials: true // enable set cookie
}));

推荐阅读