My problem:
When I go to server adress (so I’m using get method) it is working as I would want it to work, the sessionID doesn’t change upon HTTP requests, but when I’m using client’s fetch
method to get to the server adress, the sessionID always changes and that is defect, what I don’t want.
Any ideas why this is happening and how could I fix it?
Code of how my sessions are set up:
const session = require('express-session'); ... app.set("trust proxy", 1); app.use( session({ secret: process.env.SESSION_SECRET, saveUninitialized: true, resave: false, cookie: { secure: false, sameSite: true, }, }) ); ... app.get("/lobby/:id", (req, res) => { console.log(req.sessionID); req.session.test = 1; });
Client’s request
useEffect(() => { fetch(getServerAdress() + "/lobby/" + code, { method: "GET", }) .then((response) => response.json()) .then((data) => setLoading(false)) .catch(() => setLoadingText("Failed to join the lobby")); // eslint-disable-next-line react-hooks/exhaustive-deps }, []);
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
As Mat J. said, fetch does not send cookies for cross-origin by default, so I had to change it:
fetch(getServerAdress() + "/lobby/" + code, { method: "GET", credentials: "include", }
Also I had to enable credentials and origin for CORS on my server:
const cors = require("cors"); app.use(cors({ credentials: true, origin: true }));
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0