繁体   English   中英

如何解决“Cross-Origin Request Blocked”错误?

[英]How to solve “Cross-Origin Request Blocked” error?

我有CORS的问题。 我已经在谷歌搜索了很多次来解决这个问题,但是没有用。

我使用外部popup.js文件创建一个弹出对话框程序。 当我从同一个项目( myweb.com )中的任何页面调用该文件时,此js文件可以显示弹出对话框。

但问题是当我从这样的另一个网站调用这个js文件时,

<script type="text/javascript" src="http://www.myweb.com/admin/popup.js"></script>
<script> document.addEventListener("DOMContentLoaded", function(event) {
    create_popup();
}); 
</script>

我收到这个错误,

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.myweb.com/admin/get_data.php?t=0.4987759219367701.
(Reason: missing token 'access-control-allow-methods' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

在我的js文件中,我使用ajax运行get_data.php文件。 这是我的js文件,

function create_popup() {

    var xmlhttp = new XMLHttpRequest();
    if("withCredentials" in xmlhttp){
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var arr = JSON.parse(xmlhttp.responseText);
                alert(arr);
            }
        xmlhttp.open("GET","http://www.myweb.com/admin/get_data.php?t="+Math.random(),true);
        xmlhttp.setRequestHeader( "Pragma", "no-cache" );
        xmlhttp.setRequestHeader( "Cache-Control", "no-cache" );
        xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");
        xmlhttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
        xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET");
        xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
        xmlhttp.send();
    }else{
        alert("error");
        console.log("error");
    }   
}

此js文件仅适用于myweb.com 但是当我尝试从另一个网站调用这个js时,我得到了CORS错误。

我还在get_data.php文件中添加了CORS标头,如下所示,

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");

但它不起作用。 我不确定js和php文件中的头部声明是否正常。 我尝试了很多,但我不知道如何解决。

我已经尝试使用带有Allow-Control-Allow-Origin扩展的chrome浏览器。 但我看不到弹出窗口和错误。 我不知道哪个部分是错的。 我非常感谢你的建议。

(Reason: missing token 'access-control-allow-methods' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

这表明预检失败了

预检仅在某些条件下发生,其中一种情况是向请求添加“自定义”标题

因为你错误地将标题添加到你的请求中(标题只作为响应标题才有意义)

   xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");
   xmlhttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
   xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET");
   xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");

触发预检(因为它们是自定义标题) - 您的服务器无法处理(甚至不允许)预检,因此预检错误

删除那些setRequestHeader行,它应该工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM