How to use CORS to allow cookies to be set
P粉765684602
2023-08-29 17:26:51
<p>I've looked at other related posts but none of them worked for me. I use vue on the client side and node on the server side. </p>
<p>I tried the approach suggested in other posts using the cors library without success.
One might think that the following code would allow me to send requests from the client's localhost:8080 to the server's localhost:3000, but all requests fail. </p>
<pre class="brush:php;toolbar:false;">const cors = require("cors");
if (process.env.ENV !== "prod") {
let corsOptions = {
origin: ["http://localhost:8080"],
credentials: true,
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
}</pre>
<p>This is the controller I use to set cookies. </p>
<pre class="brush:php;toolbar:false;">router.route("/login").post(async (req, res) => {
//Authenticate users
const user = await Users.findOne({ where: { email: req.body.email } });
if (user == null) {
return res.status(400).send("User not found!");
}
try {
if (await bcrypt.compare(req.body.password, user.password)) {
const userInfo = {
username: user.username,
email: user.email,
age: user.age,
};
const accessToken = generateAccessToken(userInfo);
const refreshToken = jwt.sign(userInfo, process.env.REFRESH_TOKEN_SECRET);
res.cookie("token", accessToken, {
maxAge: 300000,
secure: true,
httpOnly: true,
sameSite: "none",
});
res.status(200).send("Login successful!");
} else {
res.send("Email or password is incorrect!");
}
} catch {
res.status(500).send();
}
});</pre>
<p> Basically every answer on this site falls back to app.use(cors) but for some reason that doesn't work for me. </p>
This may be because for cross-domain cookies you set {sameSite: true} and {secure: true}, but in your example you are doing it on http://localhost so it won't Set any cookies. Please refer to the link below for requirements.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
Also set the correct headers, such as Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers
You can use mkcert to refer to making a secure connection on localhost.
I also recommend using the same top-level domain on both frontend and backend, and using subdomains.
Another thing to note here is that if there is a port in the domain name, I don't think Chrome will set the cookie, please give it a try.
I successfully solved this problem so that others who come later can find the answer. I moved the declaration of cookieparser to just before where the sequelize connection is initialized. I also added the withCredentials option to my axios post request. With both steps, my cookies are now set correctly and accessible.