前言:上一篇文章提到使用JSONP实现跨域请求的时候,偶然间提到CORS,即Cross-Origin Resource Sharing(跨域资源共享)。虽然前些天也看了一下,但是今天兴趣一来还是详细地写篇博客来研究一下吧。如果是关于技术的资料,还是比较喜欢看维基百科。至于百度百科 ...
前言:上一篇文章提到使用JSONP实现跨域请求的时候,偶然间提到CORS,即Cross-Origin Resource Sharing(跨域资源共享)。虽然前些天也看了一下,但是今天兴趣一来还是详细地写篇博客来研究一下吧。如果是关于技术的资料,还是比较喜欢看维基百科。至于百度百科,平常查查生活资料还行。让我们先看看比较官方的名词解释吧,请不要吐槽我的翻译(⊙o⊙)…。
解释:
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated.[1]
A web page may freely embed images, stylesheets, scripts, iframes, videos and some plugin content (such as Adobe Flash) from any other domain. However embeddedweb fonts and AJAX (
CORS defines a way in which a browser and server can interact to safely determine whether or not to allow the cross-origin request.[2] It allows for more freedom and functionality than purely same-origin requests, but is more secure than simply allowing all cross-origin requests. It is a recommended standard of theW3C.[3]
原文解释来自维基百科
我的翻译:
跨域资源共享是一个允许网页上受限制的资源(如字体,JavaScript等)向本域名同源资源外的其他域名请求的机制。
一个网页也许能随意地嵌入任何一个域名中的图片、样式、脚步、框架、视频和一些插件(例如Adobe Flash)等内容。但是嵌入的网络字体和AJAX请求传统上被限制在只能访问主页下的同一域名(按照同源安全政策)。跨域的AJAX请求默认是被禁止的,因为它们能连同指定的自定义HTTP请求头,一起执行会带来很多跨域脚步安全问题的高级请求(如POST,PUT,DELETE和其他类型的HTTP请求)。
CORS规定了一种方法,通过这种方法浏览器和服务器之间能够安全地决定是否允许跨域请求。它比单纯的同源请求给予了更大的自由度以及功用性,但不是简单的允许所有跨域请求会更安全一些。这是W3C的一个推荐标准。
实现:
访问方法:在服务端使用'Access-Control-Allow-Origin' header进行配置。
以下前端以AJAX为例,服务端以PHP为例.
本机域名1:http://www.chengguanhui.com,本机域名2:http://www.goingic.com,请求域名是:http://www.happywzq.com。
1 var main = document.getElementById("main"); 2 var btn = document.getElementById("btn"); 3 var ajax = new 4 btn.onclick = function(){ 5 ajax.onreadystatechange=function() 6 { 7 if (ajax.readyState==4 && ajax.status==200){ 8 main.innerHTML=ajax.responseText; 9 }10 }11 ajax.open("POST","http://www.happywzq.com/xiaohui/index.php",true);12 ajax.send();13 }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:CORS(跨域资源共享)
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。