調用登陸接口時,後端通常會在調用登陸接口成功後,在response中設置cookie,以後前端的每次請求都會自動地在請求頭上加上後端設置好的cookie,這對前端來講是透明的。前端
當登陸接口與登陸後調用的接口域名不一樣時,會出現跨域問題。處理跨域問題的方式以下:ajax
前端部分:json
1 <script> 2 $(function () { 3 $.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}}); 4 }); 5 </script>
或是直接在請求中加上crossDomain:true和xhrFields後端
1 $.ajax({ 2 type: 'POST', 3 url: base + "/farmer/farmeruser/login", 4 data: pack(data), 5 contentType: 'application/json', 6 xhrFields: { 7 withCredentials: true 8 }, 9 crossDomain: true, 10 success: function (data) { 11 12 }, 13 error: function () { 14 15 } 16 })
後端部分(Java):跨域
1 private boolean recharge(HttpServletRequest request, HttpServletResponse response) throws Exception { 2 String url = request.getHeader("Origin"); 3 logger.debug("Access-Control-Allow-Origin:" + url); 4 if (!StringUtils.isEmpty(url)) { 5 String val = response.getHeader("Access-Control-Allow-Origin"); 6 if (StringUtils.isEmpty(val)) { 7 response.addHeader("Access-Control-Allow-Origin", url); 8 response.addHeader("Access-Control-Allow-Credentials", "true"); 9 } 10 } 11 return true; 12 }
首先獲取Allow-Origin的值,而後判斷是否爲空,若爲空,則給resoponse加上Allow-Orgin的值,即爲請求處的url,同時設置Allow-Credentials(容許證件)的值爲true便可。cookie
這樣設置cookie即可以成功,以後的請求都會自動加上cookie。app