跨域请求及跨域携带Cookie解决方案

2018-8-8    seo达人

如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里

Web项目前后端分离开发时,经常会遇到跨域请求和跨域携带Cookie的相关问题:

跨域请求

服务端可以根据实际需求修改下面设置,以Java代码为做示例:

 //允许跨域的域名,*号为允许所有,存在被 DDoS攻击的可能。
getResponse().setHeader("Access-Control-Allow-Origin","*");

//表明服务器支持的所有头信息字段
getResponse().setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma,Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");

/** 目前测试来看为了兼容所有请求方式,上面2个必须设 **/

//如果需要把Cookie发到服务端,需要指定Access-Control-Allow-Credentials字段为true;
getResponse().setHeader("Access-Control-Allow-Credentials", "true");

// 首部字段 Access-Control-Allow-Methods 表明服务器允许客户端使用 POST, GET 和 OPTIONS 方法发起请求。
//该字段与 HTTP/1.1 Allow: response header 类似,但仅限于在需要访问控制的场景中使用。
getResponse().setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

//表明该响应的有效时间为 86400 秒,也就是 24 小时。在有效时间内,浏览器无须为同一请求再次发起预检请求。
//请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。
getResponse().setHeader("Access-Control-Max-Age", "86400");

// IE8 引入XDomainRequest跨站数据获取功能,也就是说为了兼容IE
getResponse().setHeader("XDomainRequestAllowed","1"); 
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

跨域请求携带Cookie

服务端可以根据实际需求修改下面设置,以Java代码为做示例:

 //如果需要把Cookie发到服务端,需要指定Access-Control-Allow-Credentials字段为true;
response.setHeader("Access-Control-Allow-Credentials", "true");

//允许跨域的域名,*号为允许所有,存在被 DDoS攻击的可能。
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));

//表明服务器支持的头信息字段
response.setHeader("Access-Control-Allow-Headers","content-type"); 
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

前端根据实际情况修改发起请求的ajax,示例:

 $.ajax({
    type: "POST",
    url: "实际的请求地址",
    data: {参数:参数值},
    dataType: "json",
    crossDomain:true, //设置跨域为true xhrFields: {
              withCredentials: true //默认情况下,标准的跨域请求是不会发送cookie的 },
    success: function(data){ alert("请求成功");      
    }
}); 
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

另外还有代理、jsonp等方式不做介绍了


分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档