解决前后端分离后的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请求,这时过滤器一定得放开

  

 

posted @ 2018-02-11 17:03  二十六度半  阅读(1944)  评论(0编辑  收藏  举报