我試圖發送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
服務器將CORS標頭設置爲不是客戶端。 – Musa
所以我應該一起刪除標題?編輯:刪除它們什麼都沒做。 – Nik
你使用什麼服務器? –