【问题标题】:Ajax Jquery CORS not workingAjax Jquery CORS 不工作
【发布时间】:2016-10-22 21:56:52
【问题描述】:

大家好,我从 3 天开始就在努力寻找解决方案。我从 sharethis.com RESTapi 获取数据时遇到问题。我正在使用 jQuery 和 Laravel 5.2。我想从这个 json 中获取值:http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com 但我对尝试很多方法和函数感到非常沮丧。我的实际代码是这样的:

function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
}
$.ajax({
url: 'http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com',
type: 'GET',
beforeSend: setHeader,
contentType: 'application/json; charset=utf-8',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});

此请求始终返回“失败!”。我对 CORS 的含义有所了解,但在实践中我无法使其发挥作用。有任何想法吗?谢谢..

【问题讨论】:

  • " 我理解 CORS" ...显然你不知道,这些标头不能在请求中设置,它们必须设置在服务器端
  • 嗨@charlietfl 我把它放在我的php文件的第一行: 但不做任何改变......有什么想法吗?
  • @Francisco 这一个标题是不够的。您还需要Allow-HeadersAllow-Methods
  • 但您无法控制 sharethis.com。请求不会发送到您的服务器。

标签: javascript jquery ajax cors


【解决方案1】:

也许你真的不了解 CORS :)

这些标头必须出现在响应中,而不是请求中。

服务器必须提供它们。

服务器必须同意。

您提供的 URL 没有 CORS 标头,因此您无法通过 AJAX 获取它,除非您修改后端。

【讨论】:

    【解决方案2】:

    使用 XMLHttpRequest 运行此代码以获取数据

     var url = "http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com";
    
     var xhr = createCORSRequest('GET', url);
    
     xhr.setRequestHeader(
    
    'X-Custom-Header', 'value');
    
    xhr.withCredentials = true;
    
    xhr.onload = function () {
    
                if (this.status === 200) {
    
                    console.log(xhr);
                }
    
    };
    
    xhr.send();
    

    还有检测url是否支持CORS的功能

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

    希望对你有帮助,问候

    【讨论】:

    • 您好,感谢您的帮助,但控制台仍然显示:XMLHttpRequest 无法加载 rest.sharethis.com/v1/count/urlinfo?url=http://…。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost'。
    猜你喜欢
    • 2014-01-05
    • 1970-01-01
    • 2016-08-17
    • 2016-09-23
    • 1970-01-01
    • 2016-11-16
    • 2014-01-01
    • 1970-01-01
    相关资源
    最近更新 更多