简体   繁体   English

Express-Session 在 REST 客户端(VS Studio 扩展)上运行良好,但在 React 站点中却不行

[英]Express-Session working fine on REST-client (VS Studio extension) but not in React site

Basically, if I declare a session variable on one route, I can't access it (undefined) in another one.基本上,如果我在一条路线上声明一个 session 变量,我无法在另一条路线上访问它(未定义)。

This is my middleware:这是我的中间件:

app.use(cors({
 origin: ["http://localhost:3000"], methods: ["GET", "POST"] })); 
app.use(session({ 
 secret: process.env.SESSION_SECRET, 
 resave: false, saveUninitialized: false 
 }));

And this is my /log-in route:这是我的 /log-in 路线:

router.post('/api/users/auth/log-in/', async (req, res) => {
 // ... user authentication logic, here 'authenticated' boolean is defined 
 req.session.authenticated = authenticated; 
 req.session.save(); 
 if (authenticated) req.session.user = req.body.username; 
 res.json({"success": true, "authenticated": authenticated}); 
});

If I log the session variable inside this route, It works just fine.如果我在这条路线中记录 session 变量,它工作得很好。

But then, in another route, when accessing with req.session.authenticated , the variable returns an undefined .但是,在另一条路线中,当使用req.session.authenticated访问时,该变量返回一个undefined

I'm sure there's something I'm missing but I can't make it work.我确定我缺少一些东西,但我无法让它工作。 Any help is appreciated!任何帮助表示赞赏!

To clarify, If I do all this (logging in and checking if I'm authenticated) from REST client, it works fine.澄清一下,如果我从 REST 客户端执行所有这些操作(登录并检查我是否已通过身份验证),它工作正常。

If it works fine via your REST client and not via the app, it probably means the cookie is not being sent.如果它通过您的 REST 客户端而不是通过应用程序正常工作,则可能意味着未发送 cookie。 Have you checked the requests int the developer tools network tab?您是否检查了开发人员工具网络选项卡中的请求?

Just a small note on your code:只是对您的代码的一个小注释:

// this has no impact because after this route completes, req is destroyed. 
// It is the express-session middleware that will pickup the cookie 
// and populate the req.session object for incoming each request.
if (authenticated) req.session.user = req.body.username; 

Turns out I was missing the credentials handling on each fetch, so the cookie wasn't been sent原来我错过了每次获取的凭据处理,所以没有发送 cookie

Adding credentials: 'include' to every fetch request solved it.向每个获取请求添加credentials: 'include'解决了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM