我在两个不同的域中有两个网络应用程序 WebApp1 和 WebApp2。
- 我在 HttpResponse 的 WebApp1 中设置 cookie。
- 如何从 WebApp2 中的 HttpRequest 读取相同的 cookie?
我知道这听起来很奇怪,因为 cookie 是特定于给定域的,我们无法从不同的域访问它们;不过,我听说过跨域 cookie,它可以在多个网络应用程序之间共享。如何使用跨域cookie来实现这个要求?
注意:我正在尝试使用 J2EE webapps
最佳答案
是的,完全可以通过domain2.example
从domain1.example
获取cookie。我的社交网络的社交插件也遇到了同样的问题,经过一天的研究,我找到了解决方案。
首先,在服务器端您需要具有以下 header :
header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");
在 PHP 文件中,您可以使用 $_COOKIE[name]
第二,在客户端:
在您的 AJAX 请求中,您需要包含 2 个参数
crossDomain: true
xhrFields: { withCredentials: true }
示例:
type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
}
关于cookies - 跨域 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47250393/