2014-05-04 37 views
0

我已经跟着一个教程(并阅读了许多其他人)关于做跨域请求,但我不能让它的工作。我不断收到相同的错误:我怎样才能使这个跨域AJAX调用到API

没有'Access-Control-Allow-Origin'标头出现在请求的资源上。

这是我正在使用的代码。我正在尝试使用coinbase API。

// Create the XHR object. 
    function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
     // XHR for Chrome/Firefox/Opera/Safari. 
     xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
     // XDomainRequest for IE.                                       xhr = new XDomainRequest(); 
     xhr.open(method, url);                                       } else { 
     // CORS not supported.                                       xhr = null; 
    }                                             return xhr; 
    } 

// Make the actual CORS request. 
    function makeCorsRequest() {                                      // All HTML5 Rocks properties support CORS. 
    var url = 'https://www.coinbase.com/api/v1/prices/historical'; 
    var xhr = createCORSRequest('GET', url);                                   if (!xhr) { 
     alert('CORS not supported');                                      return; 
    }                                                                                         // Response handlers. 
    xhr.onload = function() { 
     var text = xhr.responseText;                                      var title = getTitle(text); 
     alert('Response from CORS request to ' + url + ': ' + title); 
    }; 

    xhr.onerror = function() { 
     alert('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
    } 

    makeCorsRequest(); 
+0

[No'Access-Control-Allow-Origin'标头存在于请求的资源上。为什么当我使用POSTMAN时没有显示?](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource-w) –

回答

0

默认情况下,您不允许进行跨域AJAX调用。如果目标定义了CORS策略,那么这个规则可以放宽。 Details

如果您控制目标,您应该能够通过添加CORS策略来实现此目标。