2014-02-08 37 views
11

我試圖發送XMLHttpRequest到粘貼網站。我發送一個包含api需要的所有字段的對象,但是我一直在收到這個問題。我已經讀過這個問題,我想:JavaScript - XMLHttpRequest,訪問控制 - 允許來源錯誤

httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); 

會解決它,但它沒有。有沒有人有任何關於這個錯誤的信息和/或我如何解決它?

這裏是我的代碼:

(function() { 

    'use strict'; 

    var httpReq = new XMLHttpRequest(); 
    var url = 'http://paste.ee/api'; 
    var fields = 'key=public&description=test&paste=this is a test paste&format=JSON'; 
    var fields2 = {key: 'public', description: 'test', paste: 'this is a test paste', format: 'JSON'}; 

    httpReq.open('POST', url, true); 
    console.log('good'); 

    httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); 
    httpReq.setRequestHeader('Content-type', 'application/ecmascript'); 
    httpReq.setRequestHeader('Access-Control-Allow-Origin', '*'); 
    console.log('ok'); 

    httpReq.onreadystatechange = function() { 
     console.log('test'); 
     if (httpReq.readyState === 4 && httpReq.status === 'success') { 
      console.log('test'); 
      alert(httpReq.responseText); 
     } 
    }; 

    httpReq.send(fields2); 

}()); 

這裏是確切的控制檯輸出:

good 
ok 
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. http://paste.ee/api 
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. index.html:1 
test 

這裏是控制檯輸出,當我在本地測試定期Chromium瀏覽器:

good 
ok 
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. index.html:1 
test 
+0

服務器將CORS標頭設置爲不是客戶端。 – Musa

+0

所以我應該一起刪除標題?編輯:刪除它們什麼都沒做。 – Nik

+0

你使用什麼服務器? –

回答

23

我想你已經錯過了訪問控制點。

快速回顧一下爲什麼CORS存在: 由於從網站的JS代碼可以執行XHR,該網站可能會請求發送到其他網站,僞裝成你和利用的信任那些對你網站(例如,如果您已經登錄,惡意網站可能會嘗試提取信息或執行您不想要的操作) - 這稱爲CSRF攻擊。爲了防止這種情況發生,網頁瀏覽器對你可以發送的XHR有非常嚴格的限制 - 你通常僅限於你的域名,等等。

現在,有時網站允許其他網站與其聯繫 - 提供API或服務的網站(如您試圖訪問的網站)將成爲主要候選人。開發CORS是爲了允許A站點(例如paste.ee)說「我信任站點B,所以你可以從它發送XHR給我」。這由站點A在其響應中發送「Access-Control-Allow-Origin」標頭指定。

在您的具體情況下,似乎paste.ee不打擾使用CORS。您最好的選擇是聯繫網站所有者,找出原因,如果您想使用paste.ee和瀏覽器腳本。或者,您可以嘗試使用擴展名(這些擴展名應具有更高的XHR權限)。

+0

謝謝,這正是我需要知道的。 – Nik

+2

我得到了Koy得到的同樣的錯誤,但直到現在我還沒有得到解決方案。你能告訴我,我應該在哪裏添加標題「Access-Control-Allow-Origin」?它應該在JavaScript或服務器端? – 2014-06-18 08:18:30

+1

服務器 - 請參閱http://enable-cors.org/resources.html – Sacho

0

我得到了同樣的問題。 這些服務器日誌顯示:

DEBUG: <-- origin: null 

我研究了它發生的時候我已經從本地驅動器上的文件調用,這是不填充。當我將文件複製到服務器並從服務器使用它時 - 請求的工作狀態非常好

相關問題