2015-12-24 71 views
0

我有問題與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文件我跑的get_data.php文件使用ajax。這是我的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文件中。我嘗試了很多,但我不知道如何解決。

而我已經嘗試在Chrome瀏覽器中使用Allow-Control-Allow-Origin擴展名。但我看不到彈出窗口和錯誤。我不知道哪部分是錯的。我非常感謝你的建議。

+0

** ** DONT'設置訪問在請求中添加-Control- *標題 - 添加「自定義」標題會導致在飛行前,並且您的服務器端只允許使用GET,並且可能無法正確處理預飛行 –

+0

當您在網絡選項卡中查看請求時,你看到你的標題? – epascarello

+0

你的意思是我需要刪除它。對? – Cloud

回答

2
(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線,它應該工作

+0

我按照你的說法測試,但它不起作用。 – Cloud

+1

'它不工作... ...同樣的錯誤?不同的錯誤?它是否重新編程你的錄像機?魔鬼在詳細 –

+0

是的,我得到同樣的錯誤,然後我刪除該行。 – Cloud