这样的错误,一般是由于CORS跨域验证机制设置不正确导致的,本文将详细讲解CORS跨域验证机制的原理,让您轻松掌握CORS跨域设置的使用方法,安全、方便的进行前端开发。

CORS(Cross-Origin Resource Sharing 跨源资源共享),当一个请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

例如最常见的,在一个域名下的网页中,调用另一个域名中的资源。
CORS——跨域请求那些事儿

相对于上面这种静态的调用方式,还可以通过Ajax技术来动态发起跨域请求。例如如下的方式,利用XMLHttpRequest对象发送一个GET请求,获取另一个域名下的图片内容。

<!DOCTYPE html> 
<html>
    <head>CORS Test</head>
    <body>
        <div id="img_Div"></div>
    <script type="text/javascript">  
        //XmlHttpRequest对象  
        function createXmlHttpRequest(){  
            if(window.ActiveXObject){ //如果是IE浏览器  
                return new ActiveXObject("Microsoft.XMLHTTP");  
            }else if(window.XMLHttpRequest){ //非IE浏览器  
                return new XMLHttpRequest();  
            }  
        }  

        function getFile() {
            var img_Container = document.getElementById("img_Div");
            var xhr = createXmlHttpRequest();
            xhr.open('GET', 'http://oss.youkouyang.com/1.jpg', true);
            xhr.setRequestHeader('Content-Type', 'image/jpeg');
            xhr.responseType = "blob";
            xhr.onload = function() {
                if (this.status == 200) {
                    var blob = this.response;
                    var img = document.createElement("img");
                    img.onload = function(e

相关文章: