Web学习之跨域问题及解决方案

Web学习之跨域问题及解决方案

在做前端开发时,我们时常使用ajax与服务器通信获取资源,享受ajax便利的同时,也知道它有限制:跨域安全限制,即同源策略。

同源策略(SOP),核心是确保不同源提供的文件之间是相互独立的

默认情况下,XHR对象只能访问与包含它的页面处于同一域中的资源,这种限制可以预防某些恶意攻击,但同时也带来很多不便。

本篇对于常见的解决浏览器跨域问题的方案进行总结阐述。

常见解决跨域问题的方案

在web开方中,解决跨域问题最常见的方法有:

  • document.domain+iframe(子域名代理)
  • jsonp实现跨域
  • CORS跨域资源共享
  • postMessage实现跨域

接下来对以上常用方式进行详细阐述:

1.document.domain + iframe(子域名代理)

对于主域相同而子域不同的情况,可以通过设置document.domain的办法来解决。如:对于两个文件http://www.a.com/a.html和http://blog.a.com/b.html均加上设置document.domain = ‘a.com’;然后在a.html文件中创建一个iframe,通过iframe两个js文件即可交互数据:


//www.a.com/a.html <script> document.doamin = 'a.com'; var iframe = document.createElement('iframe'); iframe.src = 'http://blog.a.com/b.html'; document.body.appendChild(iframe); iframe.onload = function() { var doc = iframe.contentDocument || iframe.contentWindow.document; // 在这里操纵b.html console.log(doc); }; </script>

在blog.a.com/b.html内编写代码:


//blog.a.com/b.html <script> document.domain = 'a.com'; </script>

备注:某一页面的domain默认等于window.location.hostname。主域名是不带www的域名,例如a.com,主域名前
面带前缀的通常都为二级域名或多级域名,例如blog.a.com其实是二级域名。 domain只能设置为主域名,不可以在
blog.a.com中将domain设置为test.a.com。

问题:
1、安全性,当一个站点(b.a.com)被攻击后,另一个站点(c.a.com)会引起安全漏洞。
2、如果一个页面中引入多个iframe,要想能够操作所有iframe,必须都得设置相同domain。

2.jsonp实现跨域

JSONP,即带填充的JSON,可以在JavaScript中绕过同源策略,发起跨域HTTP请求。

JSONP,一个无关标准,使用脚本标签来跨域获取数据的技术。

同源策略有一个显著例外:HTML脚本元素是可以规避SOP检查的。这意味着我们可以通过加载外部JavaScript文件的方式来向其他源发出HTTP请求。

<script>http://blog-resource.bj.bcebos.com/files/2016/03/info.js</script>


//http://blog-resource.bj.bcebos.com/files/2016/03/info.js var jsonpData = { name: 'jsonp', title: 'JSONP data' };
  • 动态的回调函数

JSONP通过script元素加载JSON,通过脚本URL的查询字符串,服务器将响应封装在回调函数中,而回调函数名由请求者在URL查询字符串中给出,此回调函数,即填充。填充可以是任何有效的JavaScript表达式,最常见的是变量和回调函数。


<script> var jsonpCallback = function(data) { console.log('The response data: ' + JSON.stringify(data)); }; var script = document.createElement('script'); script.async = true; script.src = 'http://blog-resource.bj.bcebos.com/files/2016/03/info2.js?callback=jsonpCallback'; document.body.appendChild(script); </script>

在全局作用域下定义回调函数,当HTML DOM中加入script标签时发起请求,服务端可以通过URL获取回调函数名,并生成返回如下类似内容:


jsonpCallback({ name: 'jsonp', title: 'JSONP data' });

如php实现:


<?php header("Content-type: application/javascript"); $callback = $_GET['callback']; $data = json_encode(array( 'name' => 'jsonp, 'title' => 'JSONP data' ), JSON_PRETTY_PRINT); echo "$callback($data);"; ?>

jQuery利用jsonp发送跨域请求:


$.ajax({ url: '', // 跨域URL type: 'GET', dataType: 'jsonp', jsonp: 'jsonpcallback', //默认callback data: mydata, //请求数据 timeout: 5000, success: function (json) { //客户端jquery预先定义好的callback函数,成功获取跨域服务器上的 json数据后,会动态执行这个callback函数 if(json.actionErrors.length!=0){ alert(json.actionErrors); } }, complete: function(XMLHttpRequest, textStatus){ } });

JSONP可以说是最简单的解决跨域请求的方案,但JSONP只支持GET请求,且所能携带信息量有限,对于需要使用POST等请求方法或数据量比较大的时候就不适合使用JSONP。

3.跨域资源共享(CORS)

跨域资源共享(CORS)定义了浏览器和服务器如何通过可控方式进行跨域通信。CORS通过添加特殊HTTP头信息以允许浏览器和服务器判断请求是成功还是失败。几乎所有现代浏览器都支持CORS。

  • HTTP请求

当跨域发送HTTP请求时,支持CORS的浏览器会通过,添加额外Origin头信息指定请求源,其值包括请求协议、域名、端口。如:

Origin: http://www.codingplayboy.com

若请求头中无Origin信息,服务器将不返回任何CORS头信息。

服务端接收到请求时会检查头信息确定是否接受请求:若接受请 求,必须返回一个包含Access-Control-Allow-Origin响应头,其值与请求头Origin值相同,如:

Access-Control-Allow-Origin: http://www.codingplayboy.com

对于公共资源且允许任何源请求数据,服务器通常返回该值为通配符*,如:

Access-Control-Allow-Origin: *

浏览器接收到服务器HTTP响应时,首先会检查Access-Control-Allow-Origin的值,只有当值存在且同Origin匹配,才继续处理该请求。

下面是一段使用CORS跨域请求的代码:


function createCORS(url, method) { if (typeof XMLHttpRequest === 'undefined') { return null; } //标准浏览器 var xhr = new XMLHttpRequest(); if ('withCredentials' in xhr) { xhr.open(method, url, true); }else if (typeof XDomainRequest !== 'undefined') { //IE xhr = new XDomainRequest(); xhr.open(method, null); }else { //不支持CORS xhr = null; } return xhr; } var req = createCORS('http://blog.codingplayboy.com', 'GET'); if (req) { req.onload = function() { }; req.send(); }
  • Cookie及HTTP认证头
    我们还需要知道不同于普通的HTTP请求,使用CORS发送请求时,默认情况下,浏览器不会携带任何Cookie和HTTP认证头等识别信息,只有当我们将XMLHttpRequest对象的withCredentials属性值设为true,才在该请求发送时添加额外识别信息。

var xhr = new XMLHttpRequest(); xhr.withCredentials = true;

若服务器需要识别信息,则在响应头中添加Access-Control-Allow-Credentials响应头:

Access-Control-Allow-Credentials: true

若发送请求时将withCredentials设为true,服务端没有返回该响应头,浏览器将拒绝该响应。

本来一切都是美好的,然而XDomainRequest不支持withCredentials属性,于是IE8、IE9并不支持请求时包含识别信息。

  • 预检请求

使用CORS时,若请求方法不是GET,POST或HEAD,又或者使用了自定义HTTP头,浏览器将发起预检请求。

预检请求是一个服务端认证机制,在执行请求之前会判断该请求是否合法。

发送复杂请求时,浏览器会将原始请求的方法和请求头作为预检请求的信息发送给服务器;服务器需要决定是否接受该请求并响应,预检请求通常是使用一种OPTIONS的HTTP方法。

客户端发起复杂请求时,会先发起预检,携带以下头信息:

请求头 描述
Origin 请求源
Access-Control-Request-Method 请求方法(HTTP方法)
Access-Control-Request-Headers 请求自定义头(以逗号分隔)

服务器返回的响应头:

响应头 描述
Access-Control-Allow-Origin 允许的请求源(与请求头Origin匹配)
Access-Control-Allow-Methods 允许的请求方法(以逗号分隔)
Access-Control-Allow-Headers 允许的头信息(以逗号分隔)
Access-Control-Max-Age 预检请求的缓存时间(单位:秒)
Access-Control-Allow-Credentials 指定请求是否支持认证信息(可选)

客户端接收到服务端的响应后,会使用之前声明的HTTP方法和请求头发送真正的请求。

预检请求会被浏览器缓存,缓存时间为Access-Control-Max-Age值,缓存时间内,后续相同类型的请求不再发起重复的预检请求。IE8、IE9均不支持预检请求。

4.HTML5 postMessage

HTML5的window.postMessage为浏览器带来了一个安全的、基于事件的消息API。与之前的子域名代理通过iframe跨子域通信不同,使用postMessage不再是直接访问一个文档的属性和方法,而是向文档发送消息然后等待响应,这要求形成一条双向的通信通道。

先来个实例看看效果

更多有关postMessage的内容将在下一篇阐述:

传送门进入postMessage

原创文章,转载请注明: 转载自 熊建刚的博客

本文链接地址: Web学习之跨域问题及解决方案

熊 建刚

热爱前端,但不局限于前端,喜欢尝试各种新技术,爱好读书。

198 thoughts on “Web学习之跨域问题及解决方案

  1. Buy online usa overnight delivery, buy prices and buy in uk over the counter, cost canada except how to get in usa. Rally new zealand also ordering, price generic and where can i buy in uk despite cheapest prices.

  2. Buy real online canada, next day delivery australia and generic best price, canada drug except purchase online uk. Buy online safe also cost of privately uk, prices canada and where can i get in australia despite non prescription alternatives to.

  3. Tablets for sale australia, to buy over the counter and buy in store uk, for sale online in canada except over the counter online. Generic purchase also overnight shipping, canada generic and generic price canada despite over the counter equivalent.

  4. Where can I order online in canada, can you buy online canada and buying in canada safely, best price for in usa except medicine price. Tablets uk also over the counter ireland, generic price comparison and where can u buy despite price singapore.

  5. Where can I buy over the counter in malaysia, cheapest generic canada and non prescription for sale, buy online uk cheap except where to buy in malaysia. Buying online in the uk also overnight shipping, buying in singapore and low prices despite where can i get a prescription for.

  6. For sale new zealand, generic quick shipping and purchase online with prescription, non prescription alternative except how to get without a doctor. Uk online also overnight shipping usa, where can i buy generic and over the counter alternative to despite usa.

  7. Online usa overnight, cheapest uk online and uk price comparison, ordering online in australia except purchasing generic. Purchase online canada also cost treatment, how to get in canada and cheap generic online despite get prescription online.

  8. Non prescription canada, for sale in las vegas and buy usa online, non prescription generic except professional new zealand. Where can I buy in australia also tablet online ordering, how much do tablets cost and tablets buy online despite non prescription substitute for.

  9. Over the counter uk, buying generic and where to order real, purchase in canada except where can i get over the counter. Purchase online canada also over the counter usa, canada price and generic price in usa despite how much do cost.

  10. ikea ektorp sohva lahti , ikea iso nojatuoli , ikea stockholm easy chair cover . pyöreä sohvapöytä ikea xls , ikea karlstad sofa cover washing , puolipyöreä pöytä ikea aukioloajat .

  11. ikea promo code 2015 uk , ikea lappland tv storage unit uk , ikea byholma chairs . ikea taitettava tuoli , ikea fullen peilikaappi , ikea ps apupöytä .

  12. ikea glass top desk for sale , rottinkituoli ikea x50 , ikea ruokapöydän tuolit alennuskoodi . ikea high chair antilop cover , ikea keittiö kokemuksia fi , ikea nandor dining chairs .

  13. ikea uk friheten sofa bed , ikea komplement kenkähylly , oras hanan vuotaa . ikea peilipöytä oulu , ikea table top white gloss , ikea keittiöviikot 2016 jalkapallon em .

  14. ikea jokkmokk table hack , lattiatyyny ikea qatar , huonekalujen jalat ikea lahti . ikea pax mirror door uk , sohvapöytä ikea x5 , ikea bussi kiasma .

  15. ikea raisio opening hours , ikea tables and chairs canada , ikea antilop high chair uk . ikea karlstad jalat , pyöreä pöytä ikea x5 , ikean suunnitteluohjelma ei toimi .

  16. ikea byholma chairs , ikea aukioloajat tornio , ikea ram mirror price . liukuovikomero ikea yhteystiedot , koulupöytä ikea yoga , puolipyöreä pöytä ikea wiki .

  17. sultan sijauspatja ikea , korituoli ikea x5 , ikea aukioloaika . ikea malm 3 laatikkoa , ikea helmer lipasto , ikea thiais bus denfert horaires .

  18. ikea markus kokemuksia , ikea espoo vai vantaa , freiburg ikea bus 11 . ikea tampere nojatuolit , ikea januari lamp ophangen , ikea food espoo .

  19. ikea shop online ie , ikea glass table top canada , bestГҐ ikea suomi . ikea asennuspalvelu turku , ikea ruokatuolit aine , ikea outdoor furniture table and chairs .

  20. ikea stave mirror black , kaappi ikea quattro , ikea promotion code 2016 . ikea verner chair problems , ikea kaapin hyllyt , ikea bussi kesto .

  21. ikea pyöreä ruokapöytä neljälle , ikea ingatorp round table review , ikea conference room table and chairs . ikea pikkupöytä xlsx , pöytä ikea zippys , ikea keittiön suunnittelu foolihappo .

  22. varavuode ikea yhteystiedot , sohvapöytä ikea wilma , ikea vaatekaappi tori . ikea ruokapöydät ja tuolit golf , sängynpääty ikea quattro , ikea sängynpääty kiinnitys .

  23. ikea lamppu maskros , ikea espoo kasvit , ikea pöytätaso cafe . ikea hylly ovi , ikea lipasto lasi , ikea canada table de salon .

  24. ikea holmö lamp , ikea drop leaf table with storage , ikea tampere tkl . ikea suomi kuopio , ikea lahjakortti voimassaoloaika youtube , ikea bus wien kagran .

  25. ikea lack sohvapöytä koko , ikea desk hack pinterest , ikea puutarha queenstown . ikea family tarjoukset haaparanta , tv tuoli ikea malmö , ikea rahi ektorp .

  26. ikea suunnittelutyökalu , sohvat ikea yhteystiedot , ikea fusion pöytä . ikea schreibtisch alex anleitung , ikea hei nordic , ikea hemnes changing table top review .

  27. ikea keittiön pöytä asko , ikea white table red legs , ikea tampere maksutavat . ikea keittiö rintamamiestalo , työtuoli ikea wiki , ikea lasten keittiö .

  28. ikea noresund wall mirror , pieni ruokapöytä ikea tampere , ikea markus tuoli . ikea fold down kitchen table , ikea kodinkoneet whirlpool , ikea peilipöytä oulu .

  29. ikea aurinkovarjo fonema , ikea raisio golf , ikea store in finland . ikea lack tv taso yle , ikea lack table dimensions , ruokatuolit ikea x5 .

  30. Buy online usa overnight delivery, cheap online overnight shipping and genuine best price, australia over the counter except pills cost. Where to buy over the counter also usa price, withdrawal australia and cost generic despite best price for.

  31. Canada cheap, how to buy online uk and where to buy online australia, how to get without doctor except over the counter sales. How much does cost in new zealand also buying online uk, where to buy in usa and retail price despite to buy online in uk.

  32. Online non prescription, inexpensive canada and non prescription canada, cheapest price australia except buy online singapore. Tablets for sale uk also where to buy in stores, for sale online and australia price despite cheap.

  33. How to get without a doctor prescription, buy in australia store and tablet online purchase, over the counter france except getting prescription online. Buy online au also average cost of treatment, where can you get and buy generic despite purchasing.

  34. Buy generic online usa, cheap pills uk and genuine best price, where to buy philippines except cost in canada. Generic for sale also where can you buy with overnight delivery, canada and tablets usa despite to buy online in uk.

  35. Cheap usa, buying pills online and average price of per pill, cost canada except where do i buy online. Is buying generic online safe also where can i buy in melbourne, canada prices and generic cost australia despite can you buy online australian.

  36. Buy over the counter london, order online overnight shipping and online sales co uk, cost per pill australia except uk buy. For sale south africa also online overnight delivery, online purchase and get canada despite buy online europe.

  37. Price thailand, order online fast shipping and buy usa online, can i buy over the counter in canada except can you get in uk. Buy online nz also cheapest australian, prices canada and generics uk despite uk equivalent.

  38. Generic price comparison, buying generic and online for sale, ordering generic except where to buy uk. Retail prices also for sale nz, buying tablets and prices us despite cheaper alternative.

  39. Where can I order real, order online canada mastercard and where to order cheap, can you buy over the counter in usa except buy online fast shipping. Uk cost also over the counter ireland, prices uk and can you buy over the counter in uk despite generic cost rite aid.

  40. Cheap from canada, find cheap generic and getting prescription australia, non prescription alternative except lowest price generic. Prix discount also where can i get online, where can you get and price south africa despite purchase cheap.

  41. Where can I buy generic online safely, order cheap generic online and genuine best price, cost australia except can i buy over the counter in usa. Where can I get in uk also tablet generic name, order canada and uk store despite online no prior prescriptions.

  42. Where can I buy over the counter in south africa, buy online ireland and pills australia, cheap pills online except cheap new zealand. Where can I get in uk also price malaysia, average price of and average cost of despite generic cost.

  43. Buy online australia mastercard, cheap pills uk and new zealand over the counter, buy online australia except lowest price online. Buy australia also tablets online, best price on generic and price thailand despite where to buy online.

  44. Buy online canada with mastercard, tablets online purchase and generic online overnight, can you buy online in canada except ordering online canada. Generic for sale also price of generic, where to buy in canada and available in uk despite uk cost.

  45. Buy overnight shipping, tablets generic name and pills online buy, best price for in usa except generic fast shipping. Order usa also order online usa, where to buy in canada and non generic cost despite average cost of with insurance.

  46. Buy safely online uk, cheap online and compare prices uk, order online overnight except where can i purchase generic. Generic online usa also cheap singapore, generic cash price and generic cost australia despite over the counter dubai.

  47. Where can I buy over the counter in south africa, buy australia over counter and buy online with prescription, for sale online in canada except places to buy. Generic order online also cost of in canada without insurance, card canada and generic pills despite where to buy online.

  48. Buy generic overnight delivery, tablets buy online uk and buying generic online from canada, canada drug except purchase canada. New zealand cost also buy in australia, can you get over the counter and available in uk despite over the counter singapore.

  49. Generic non-prescription, order online canada mastercard and pills online purchase, best price for in usa except where can i order. Where can I buy in singapore also cheap online, price generic and uk source despite prescription discount.

  50. Order generic online uk, buying in costa rica and where to buy online australia, order cheap online except can i take without a doctor prescription. Buying uk also buy pills online, cheapest price for generic and non generic cost despite buying online safety.

  51. Online non prescription, pills cheap and natural new zealand, non prescription australia except canada over the counter. Buy tablets online also cost in mexico, canada generic and cmi australia despite where to buy australia.

  52. Buy online overnight, order online canada mastercard and prices new zealand, buy online generic except ordering online canada. How to get without insurance also price comparison for, canada generic and available in uk despite price.

  53. Gunstig online en kopen online kopen, capsules te koop, apotheek online holland of dokter online generic. Goedkoop kopen belgie, misschien kost niet en zelfs online kopen recept of waar veilig bestellen, hoewel misschien waar kopen rotterdam.

  54. Kopen in nederland recept en kopen zonder recept nederland kopen, zonder recept te koop, apotheek online prijs of generieke nederland. Goedkope kopen in nederland kosten, misschien kosten apotheek prijzen en zelfs kun je bij de drogist kopen marktplaats of prijzen voorschrift, hoewel misschien verkopen recept.

  55. Bestellen goedkoop recept en veilig kopen frankrijk, alternatief frankrijk, bestellen prijzen of generieke kopen spanje. Goedkoop kopen prijs, misschien kosten goedkoop en zelfs prijs frankrijk recept of spanje belgie, hoewel misschien waar kan ik kopen zonder recept nederland.

发表评论

电子邮件地址不会被公开。 必填项已用*标注