ajax 跨域無法攜帶cookie,需要用到session,終於完美結局
xhrFields: {
withCredentials: true
},
添加這個可能是大家都會做的一件事
但是添加上了之后就出現了另外一個問題
The 'Access-Control-Allow-Origin' header contains the invalid value 'Origin'. Origin 。。。。。。
2、服務器server端要配置Access-Control-Allow-Credentials
我們在客戶端設置了withCredentials=true
參數,對應着,服務器端要通過在響應 header 中設置Access-Control-Allow-Credentials = true
來運行客戶端攜帶證書式的訪問。通過對Credentials參數的設置,就可以保持跨域Ajax時傳遞的Cookie。
response.setHeader("Access-Control-Allow-Credentials", "true");
3、服務器server端要配置Access-Control-Allow-Origin
到以上配置為止,發送ajax請求,我們發現還會出現一個錯誤,提示我們 Access-Control-Allow-Origin
不能用 *
通配符。原因是:當服務器端 Access-Control-Allow-Credentials = true
時,參數Access-Control-Allow-Origin
的值不能為 '*'
。
我們重新設置Access-Control-Allow-Origin的值,當服務器端接收到請求后,在返回響應時,把請求的域Origin填寫到響應的Header信息里(即誰訪問我,我允許誰),代碼如下:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
添加了這個就可以了