否'访问控制允许来源'当跨域设置为true时,请求的资源错误中存在标头

No 'Access-Control-Allow-Origin' header is present on the requested resource error when cross domain set to true

本文关键字:请求 资源 存在 true 错误 设置 访问控制      更新时间:2024-03-06

我正试图使用此url发出AJAX请求http://api.adorable.io/avatars/285/sd我已经将crossDomain设置为true,但每次请求都会失败,并出现此错误。

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

无法使用发出请求http://www.api.adorable.io/avatars/285/sd.我怎么了?请帮助

$(document).ready(function(){    
 $.ajax({
        url: "http://api.adorable.io/avatars/285/sd",
        type: "GET",
        crossDomain: true, // enable this
        success: function (data) {
           console.log(data);
        }
    });
});

仅仅在Ajax调用(您正在调用的文件)中设置它是不够的(http://api.adorable.io/avatars/285/sd)需要标头以允许跨域调用。

header('Access-Control-Allow-Origin: *');

将是为PHP添加的代码,以允许所有起源。如果您只想允许特定的域,请将*更改为您的域。

由于您无法控制该URL,因此需要一个好的变通方法。您可以做的是在本地创建一个您控制的PHP文件,该文件使用cURL通过他们的API从adomble.io获取您正在调用的资源,并使用Ajax请求调用本地PHP脚本。然后,您就不必担心Ajax中的跨域问题,一切都会正常工作。为流程增加了少量开销,但这是一个简单的解决方法。

相关文章: