jQuery-跨域問題的處理


調用登錄接口時,后端一般會在調用登錄接口成功后,在response中設置cookie,之后前端的每次請求都會自動地在請求頭上加上后端設置好的cookie,這對前端來說是透明的。

當登錄接口與登錄后調用的接口域名不同時,會出現跨域問題。處理跨域問題的方式如下:

前端部分:

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。


免責聲明!

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



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