首页  >  问答  >  正文

如何使用CORS来允许设置Cookie

<p>我已经查看了其他相关的帖子,但都对我没有用。我在客户端使用vue,在服务器端使用node。</p> <p>我尝试了其他帖子中建议的使用cors库的方法,但没有成功。 人们可能会认为下面的代码可以让我从客户端的localhost:8080发送请求到服务器的localhost:3000,但是所有的请求都失败了。</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>这是我用于设置cookie的控制器。</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("找不到用户!"); } 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("登录成功!"); } else { res.send("邮箱或密码不正确!"); } } catch { res.status(500).send(); } });</pre> <p>这个网站上的每个答案基本上都会回到app.use(cors),但出于某种原因,对我不起作用。</p>
P粉765684602P粉765684602416 天前378

全部回复(2)我来回复

  • P粉514001887

    P粉5140018872023-08-30 16:22:05

    这可能是因为对于跨域的cookie,您设置了{sameSite:true}和{secure:true},但在您的示例中,您是在http://localhost上进行的,因此不会设置任何cookie。请参考以下链接以获取要求。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure

    还要设置正确的头部,例如Access-Control-Allow-Credentials,Access-Control-Allow-Origin,Access-Control-Allow-Headers

    您可以使用mkcert来参考在本地主机上进行安全连接。

    我还建议在前端和后端使用相同的顶级域,并使用子域。

    这里还要注意的一点是,如果域名中有端口,我认为Chrome不会设置cookie,请尝试一下。

    回复
    0
  • P粉647449444

    P粉6474494442023-08-30 09:52:10

    我成功解决了这个问题,以便后来的人可以找到答案。我将cookieparser的声明移到了初始化sequelize连接的位置之前。我还在我的axios post请求中添加了withCredentials选项。通过这两个步骤,我的cookie现在都正确设置并且可以访问。

    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: "电子邮件或用户名已被使用!",
                })
              );
          },

    回复
    0
  • 取消回复