【发布时间】:2015-12-24 02:40:08
【问题描述】:
我对 CORS 有疑问。我已经在谷歌搜索了很多次来解决这个问题,但是没有用。
我使用外部 popup.js 文件制作了一个弹出对话框程序。当我从同一项目中的任何页面调用该文件时,此 js 文件可以显示弹出对话框(myweb.com)。
但问题是当我像这样从另一个网站调用这个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 浏览器中进行了尝试。但我看不到弹出窗口和错误。我不知道哪一部分是错的。非常感谢您的建议。
【问题讨论】:
-
DONT 在请求中设置
Access-Control-*标头 - 添加“自定义”标头会导致预飞行,并且您的服务器端仅允许GET并且可能无法处理无论如何正确地预飞行 -
当您在网络选项卡中查看请求时,您是否看到了您的标头?
-
你的意思是我需要删除它。对吗?
-
是的,我可以看到我的标题。
标签: javascript php jquery ajax