cookies未被发送到浏览器

发布于 2025-01-27 10:51:09 字数 948 浏览 3 评论 0 原文

我有一个由React和Express JS进行的全堆栈项目。目前,两者都是在Heroku中作为两个不同的项目托管的(frontend: x.Herokuapp.com ;后端: y.herokuapp.com )。

这是问题。每当我尝试登录该应用程序时,都不会在浏览器上设置cookie。浏览器中的cookie存储为空,因此请求失败。错误可能在哪里?

这是设置会话的代码:

app.use(session({
  name: "irmp_session",
  secret: process.env.SESSION_KEY,
  resave: false,
  saveUninitialized: true,
  httpOnly: false,
  maxAge: 7200000, // 2 hrs validity
  store: MongoDBStore,
  cookie: {
    path: "/",
    secure: true,
    sameSite: 'none'
  }
}))

以及执行请求的前端代码:

const URL = 'https://y.herokuapp.com/';

const http = axios.create({
  baseURL: URL,
  headers: {
    "Content-type": "application/json",
    "Access-Control-Allow-Credentials": true
  },
  credentials: 'same-origin'
});

  fetchUserInformation() {
    return http.get("/users/profile", { withCredentials: true });
  }

我阅读的一些文章将我指向了CORS问题,但我不知道该如何真正修复它。任何线索都非常感谢。

I have a full-stack project that I made with React and Express JS. Both are currently hosted in heroku as two different projects (frontend: x.herokuapp.com; backend: y.herokuapp.com).

Here's the problem. Whenever I try to log in to the app, the cookie is not being set on the browser. The cookie storage in the browser is empty, therefore the request fails. Where could the error be?

Here's the code that sets the session:

app.use(session({
  name: "irmp_session",
  secret: process.env.SESSION_KEY,
  resave: false,
  saveUninitialized: true,
  httpOnly: false,
  maxAge: 7200000, // 2 hrs validity
  store: MongoDBStore,
  cookie: {
    path: "/",
    secure: true,
    sameSite: 'none'
  }
}))

And the frontend code that does the request:

const URL = 'https://y.herokuapp.com/';

const http = axios.create({
  baseURL: URL,
  headers: {
    "Content-type": "application/json",
    "Access-Control-Allow-Credentials": true
  },
  credentials: 'same-origin'
});

  fetchUserInformation() {
    return http.get("/users/profile", { withCredentials: true });
  }

Some articles I've read are pointing me to a CORS issue, but I don't know how to fix it really. Any leads are greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橪书 2025-02-03 10:51:09

可能是因为 *.herokuapp.com在公共后缀列表中列出,从而阻止您在服务器端设置cookie。
https://devcenter.heroku.com/articles/articles/cookies-coookies-andceies-and-herokuapp--herokuapp-- com

相关问题:

请注意,自定义域将没有此问题,但是您必须使用付费计划来在自定义域上获取免费的SSL

Could be because *.herokuapp.com is listed in the Public Suffix List, preventing you to set a cookie on the server side.
https://devcenter.heroku.com/articles/cookies-and-herokuapp-com

Related question:
Express/Heroku - Cookie set on server web app instead of client web app

Note that a custom domain will not have this problem, however you have to use a paid plan to get free SSL on custom domain

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文