1. 程式人生 > >跨域請求設置withCredentials(轉)

跨域請求設置withCredentials(轉)

exce with 代碼 debug .get number alt cti post

  最近在做運動城項目,這一個項目下面有多個子項目,如主數據項目,pos項目等。主數據項目的域名為www.topmall.com,POS項目的域名為pos.topmall.com。即兩個項目的主域名相同,子域名不相同。

  我們的登陸認證是放在主數據項目的,即進入POS項目如果檢測未登陸,是先要調用主數據的一個登陸接口登陸後才可以訪問的。這時候跨域問題就出現了,進入POS項目之後跳出登陸框,輸入用戶名密碼請求主數據的http://www.topmall.com/signin進行登陸,看到返回的response裏面也有Set-cookie,但是再次請求POS項目的http://pos.topmall.com/pos/cashier/info 資源時卻報錯了。調試進去看發現後臺獲取不到當前登陸的用戶,查看請求頭發現並沒有把登陸時返回的cookies設置到第二次請求的頭裏面。

  查詢資料才知道登陸請求的主數據項目與POS項目不屬於同一個子域,即存在跨域,跨域請求想要帶上cookies必須在請求頭裏面加上{crossDomain: true, xhrFields: {withCredentials: true}}設置,於是在index界面加上了如下代碼:

1 2 3 4 5 <script> $(function () { //, headers: { ‘x-requested-with‘: ‘XMLHttpRequest‘ } $.ajaxSetup({crossDomain: true, xhrFields: {withCredentials:
true}}); }); </script>

  然後在後臺代碼返回response時做如下處理:

1 2 3 4 5 6 7 8 9 10 11 12 private boolean recharge(HttpServletRequest request, HttpServletResponse response) throws Exception { String url = request.getHeader("Origin"); logger.debug("Access-Control-Allow-Origin:"
+ url); if (!StringUtils.isEmpty(url)) { String val = response.getHeader("Access-Control-Allow-Origin"); if (StringUtils.isEmpty(val)) { response.addHeader("Access-Control-Allow-Origin", url); response.addHeader("Access-Control-Allow-Credentials", "true"); } } return true; }

  

再次訪問,發現請求頭已經可以攜帶cookies。

跨域請求設置withCredentials(轉)