跨域問題,前端主動向后台發送cookie


跨域是什么?

從一個域名的網頁訪問另一個域名的資源,就會出現跨域。只要協議、端口、域名有一個不同就會出現跨域

例如:

1.協議不同  http://www.baidu.com:80 和 https://www.baidu.com:80

2.端口不同  https://www.badu.com:80 和 https://www.baidu.com:8888

3.域名不同 https://www.jd.com:80 和 https://www.taobao.com:80

當瀏覽器向后台發起請求時,如果是跨域請求,那么就不會發送cookie給后台,而cookie中有一些信息,例如JsessionID等身份信息就不能發送給后台,這樣會導致服務器認為你沒有登錄。

而如果前台已經解決了主動發送cookie的問題,后台如果header中沒有“Access-Control-Allow-Origin”,並且值為*或者瀏覽器當前訪問網頁的域名時,那么會直接進入ajax的error方法中,瀏覽器會直接將返回的內容丟掉。
解決方案:

前端:

1.jquery ajax

$.ajax({

url: '自己要請求的url',
method:'請求方式', //GET POST PUT DELETE
xhrFields:{withCredentials:true},
success:function(data){
//自定義請求成功做什么
},
error:function(){
//自定義請求失敗做什么
}

})

 2.angular.js

$http.get(url, {withCredentials: true});
$http.post(url,data, {withCredentials: true});
后台:java spring
response().setHeader("Access-Control-Allow-Credentials", "true");
response().setHeader("Access-Control-Allow-Origin", "login.com");

注意,這里login.com 不能設置為 * 來允許全部,如果在 Credentials 是true 的情況下。因為瀏覽器會報錯如下:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://10.0.0.3:18080' is therefore not allowed access

 所以要設置成客戶端頁面的 域名。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM