Session cookie 未随 XHR 请求一起发送

Session cookie not sending with XHR requests

我的 React 应用程序(来自域 react-app.com)加载到网站 beautiful-site.com 中,并且从 React 应用程序发送的请求没有发送关联的 session cookie有了它。

我的解决方法是在服务器中添加以下 header,并在使用 withCredentials: true

发送的 React 应用程序 XHR 请求中添加
Access-Control-Allow-Origin: https://beautiful-site.com
Access-Control-Allow-Credentials: true

问题是我可以在 Access-Control-Allow-Origin 中指定一个特定站点,因为 React 应用程序将被添加到许多站点而不是一个站点。

有什么方法可以让 session 从 React 应用程序发送 cookie 吗?

答案是否定的,但您有解决方法:当您设置 withCredentials 时,您不能拥有 Access-Control-Allow-Origin: *

修复必须在服务器端完成:您的 API 服务必须 returns Access-Control-Allow-Origin 中请求的域,通常取自 Origin header.

请参阅 No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API如何修复“Access-Control-Allow-Origin header 不能是通配符”问题 小节)了解技术细节。