【问题标题】:CORS doesn't workCORS 不起作用
【发布时间】:2014-05-15 03:00:06
【问题描述】:

我试图对雅虎的符号进行异步调用,建议JSONP API,所以有跨域问题,我已经阅读了this文档并尝试更改它的url,以下是我使用的代码

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;
            }


            function makeCorsRequest() {
                // All HTML5 Rocks properties support CORS.
      //          var url = 'http://updates.html5rocks.com';

               var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
                var xhr = createCORSRequest('GET', url);
                if (!xhr) {
                    alert('CORS not supported');
                    return;
                }

                // Response handlers.
                xhr.onload = function() {
                    var text = xhr.responseText;
                    console.log(text);
                };

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

                xhr.send();
            }

但问题仍未解决:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

有人知道为什么吗?另外,我将文档中的代码与常规的 ajax 代码进行了比较,它们几乎相同,CORS 是如何工作的? 谢谢

【问题讨论】:

    标签: jsonp cors


    【解决方案1】:

    为了使 CORS 工作,服务器需要设置 Access-Control-Allow-Origin 标头。如果你不控制服务器,而且服务器没有设置那个header,那你恐怕就不​​走运了。

    CORS 替代 JSONP 作为加载跨域 json 内容的方式,但是使用 JSONP 服务端也需要实现它。

    如果内容的所有者不希望你使用它,浏览器会拒绝它。

    编辑:当然,您可以通过让您的服务器从原始服务器获取内容并让浏览器从您自己的服务器获取内容来避免跨浏览器问题。更多的工作,但它不再是跨浏览器了。

    【讨论】:

    • 我遇到了同样的问题。显然,CORS 背后的真正想法是什么并不是很明显,但它之所以这样工作是有充分理由的。顺便说一句,我已经为我的答案添加了一个解决方法。如果对您有帮助,请随时接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 2017-01-31
    • 2016-04-22
    • 2015-03-18
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    相关资源
    最近更新 更多