跨域請(qǐng)求及跨域攜帶Cookie解決方案

2018-8-8    seo達(dá)人

如果您想訂閱本博客內(nèi)容,每天自動(dòng)發(fā)到您的郵箱中, 請(qǐng)點(diǎn)這里

Web項(xiàng)目前后端分離開發(fā)時(shí),經(jīng)常會(huì)遇到跨域請(qǐng)求和跨域攜帶Cookie的相關(guān)問(wèn)題:

跨域請(qǐng)求

服務(wù)端可以根據(jù)實(shí)際需求修改下面設(shè)置,以Java代碼為做示例:

 //允許跨域的域名,*號(hào)為允許所有,存在被 DDoS攻擊的可能。
getResponse().setHeader("Access-Control-Allow-Origin","*");

//表明服務(wù)器支持的所有頭信息字段
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");

/** 目前測(cè)試來(lái)看為了兼容所有請(qǐng)求方式,上面2個(gè)必須設(shè) **/

//如果需要把Cookie發(fā)到服務(wù)端,需要指定Access-Control-Allow-Credentials字段為true;
getResponse().setHeader("Access-Control-Allow-Credentials", "true");

// 首部字段 Access-Control-Allow-Methods 表明服務(wù)器允許客戶端使用 POST, GET 和 OPTIONS 方法發(fā)起請(qǐng)求。
//該字段與 HTTP/1.1 Allow: response header 類似,但僅限于在需要訪問(wèn)控制的場(chǎng)景中使用。
getResponse().setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

//表明該響應(yīng)的有效時(shí)間為 86400 秒,也就是 24 小時(shí)。在有效時(shí)間內(nèi),瀏覽器無(wú)須為同一請(qǐng)求再次發(fā)起預(yù)檢請(qǐng)求。
//請(qǐng)注意,瀏覽器自身維護(hù)了一個(gè)最大有效時(shí)間,如果該首部字段的值超過(guò)了最大有效時(shí)間,將不會(huì)生效。
getResponse().setHeader("Access-Control-Max-Age", "86400");

// IE8 引入XDomainRequest跨站數(shù)據(jù)獲取功能,也就是說(shuō)為了兼容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

跨域請(qǐng)求攜帶Cookie

服務(wù)端可以根據(jù)實(shí)際需求修改下面設(shè)置,以Java代碼為做示例:

 //如果需要把Cookie發(fā)到服務(wù)端,需要指定Access-Control-Allow-Credentials字段為true;
response.setHeader("Access-Control-Allow-Credentials", "true");

//允許跨域的域名,*號(hào)為允許所有,存在被 DDoS攻擊的可能。
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));

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

前端根據(jù)實(shí)際情況修改發(fā)起請(qǐng)求的ajax,示例:

 $.ajax({
    type: "POST",
    url: "實(shí)際的請(qǐng)求地址",
    data: {參數(shù):參數(shù)值},
    dataType: "json",
    crossDomain:true, //設(shè)置跨域?yàn)閠rue xhrFields: {
              withCredentials: true //默認(rèn)情況下,標(biāo)準(zhǔn)的跨域請(qǐng)求是不會(huì)發(fā)送cookie的 },
    success: function(data){ alert("請(qǐng)求成功");      
    }
}); 
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

另外還有代理、jsonp等方式不做介紹了


分享本文至:

日歷

鏈接

個(gè)人資料

存檔