站點通常採用cookie來保持用戶的登陸狀態。當涉及跨域訪問保持登陸狀態時,瀏覽器處於安全考慮默認是不會攜帶cookie,也不會跨域寫入響應頭裏的cookie到本地。這時需要前後端配合來解決:
服務器端:
header("Access-Control-Allow-Origin: http://192.168.23.144:8080"); //允許的域
header("Access-Control-Allow-Credentials: true"); //允許跨域攜帶識別信息
SetCookie("MyCc","Val888",0,'/','192.168.23.144'); //set cookie
前端:
var xhr=new XMLHttpRequest()
xhr.open("POST","http://ai.test.com/dev/login",true)
xhr.withCredentials=true
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
console.log(xhr.responseText)
}
}
xhr.send({mobile: "1300000001"})
不同框架有相應的config方式,以vue爲例:
this.$http.post(this.url + "dev/suggest", {name: this.name},{withCredentials: true})
.then(function(res) {
console.log(res)
})