How to use CORS to allow cookies to be set
P粉765684602
P粉765684602 2023-08-29 17:26:51
0
2
400
<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>
P粉765684602
P粉765684602

reply all(2)
P粉514001887

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.

P粉647449444

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.

const express = require("express");
require("dotenv").config();
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const cookieParser = require("cookie-parser");
app.use(cookieParser());
const port = process.env.PORT || 8080;
const lib = require("./lib"); //这是所有自定义函数
const sql = require("./database");
onSubmit() {
        let loginInfo = {
          email: email.value,
          password: password.value,
        };
        axios
          .post("http://localhost:3000/user/login", loginInfo, {
            withCredentials: true,
          })
          .then(() =>
            $q.notify({
              color: "green-4",
              textColor: "white",
              icon: "cloud_done",
              message: "帐户创建成功!",
            })
          )
          .catch(() =>
            $q.notify({
              color: "red-5",
              textColor: "white",
              icon: "warning",
              message: "电子邮件或用户名已被使用!",
            })
          );
      },
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template