解決前后端分離后的Cookie跨域問題



 

一. 前端Ajax關鍵配置

$.ajax({
  type: "post",
  url: xxx,
  data: xxx,
  contentType: 'application/json',
  dataType: "json",
  xhrFields: { withCredentials: true },

  success: function (data) {
  }
})

 

二、后端過濾器關鍵配置

  //解決Cookie跨域問題
  response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
  response.setHeader("Access-Control-Allow-Credentials", "true");
  response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  response.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE");

  //解決 Content-Type:application/json 時跨域設置失敗問題
  if("OPTIONS".equals(request.getMethod())) {
      //放行OPTIONS請求
      filterChain.doFilter(request, response);
      return;
  }

 

注意:

  • "Access-Control-Allow-Origin" 不能設置成 "*"
  • 當 Content-Type 為 application/json 時,Ajax實際會發兩次請求,第一次是一個OPTIONS請求,這時過濾器一定得放開

  

 


免責聲明!

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



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