天天看點

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 }