需求背景: 公司有俩网站, A站点需要拿B站点的用户登录状态,然后实现A站自动登录的功能. 然后技术实现就是A站点在浏览器客户端ajax请求B站点的接口, 这就需要在请求B站时在请求里携带Cookie来判断当前客户端B站点是否是登陆状态.
知识点: 在请求中有Request Cookies 和 Response Cookiesd 两种.
技术实现: 假设A站点为a.com, B站点为b.com
1. ajax跨域请求方式
A站点的前端代码发起跨域(a.com/index.html)
<body>
<script src="/jquery.js"></script>
<script>
$.ajax({
url:"https://b.com/test.php",
type:"GET",
xhrFields:{
withCredentials:true
},
success:function(res){
console.log(res);
}
})
</script>
</body>
B站点的后端代码(b.com/test.php)
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://a.com");
if (count($_C