ajax跨域,携带cookie

解决方案很简单。

直接上代码:

web.xml中:

添加了 cors来解决跨域

(奇怪的是,credentials设置为false。反正这个是照搬的。。。)

  <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
      <param-name>cors.allowed.origins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>cors.support.credentials</param-name>
      <param-value>false</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

或者在代码中设置:

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST");
response.setHeader("Access-Control-Allow-Credentials", "true");

ajax:

$.ajax({
type: "post",
url: "Get",
crossDomain: true, //加这二行支持ajax跨域,允许跨域
xhrFields: {withCredentials: true},//加这二行支持ajax跨域,携带凭证
success: function (data) {
alert(data); }
});

上一篇:jquery中$.get()如何让跨域请求携带cookie?


下一篇:vue踩坑(二):跨域以及携带cookie