跨域ajax请求 cookie存储

前几天做了一个项目, 前后端分离, 后端只提供接口, 遇到第一个问题,ajax请求是跨域的, 又需要登录, 准备使用原生的tomcat session 登录后记录到session里就好了。
第一个问题:ajax请求写回的cookie,不能直接写到浏览器里,每次登录都会失效,解决方案是服务器端返回头加上
response.setHeader("Access-Control-Allow-Origin",发起请求的域名例如:http://baidu.com 一定要全域名);
    response.addheader("Access-Control-Allow-Credentials","true");
    response.addheader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
    response.addheader("P3P","CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");

ajax请求时也需要加参数:

$.ajax({
                  type: "get",url: "url",dataType: 'text',xhrFields: {
                      withCredentials: true
                  },crossDomain: true,success: function(data){
                      console.log(data);
                  }
              }
      );

这样解决了, 跨域cookie传递问题, 后来就出现了一个问题, PUT , DELETE 方法请求时出现问题, 看到后台日志很明显是用OPTION 方法请求, 后来查了资料才知道, 这叫OPTION预检, 预检的时候没有在springmvc里找到对应的方法, 直接报错, 最后加上过滤器

logger.info("http method:{}",httpServletRequest.getmethod());
    if (httpServletRequest.getHeader("Access-Control-Request-Method") != null
            && StringUtils.equalsIgnoreCase("OPTIONS",httpServletRequest.getmethod()) ) {
            // CORS "pre-flight" request
            httpServletresponse.addheader("Access-Control-Allow-Origin","*");
            httpServletresponse.addheader("Access-Control-Allow-Methods",DELETE");
            httpServletresponse.addheader("Access-Control-Allow-Headers","Content-Type");
            httpServletresponse.addheader("Access-Control-Max-Age","1800");//30 min


            return;
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);

OPTION 预检直接返回,后面正常请求就能成功处理了。

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...