解决前后端分离后的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