對這個問題的工作頁面,我寫了下面的腳本:發佈使用XMLHttpRequest的
window.onload = function() {
var request = new XMLHttpRequest();
var url = "http://localhost:3000/say_hello";
var params = "username=FooMan";
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.withCredentials = true;
request.send(params);
}
但是每次我試圖執行腳本我得到
XMLHttpRequest cannot load http://localhost:3000/say_hello. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
我已經嘗試使用
request.setRequestHeader("Access-Control-Allow-Origin", "*");
request.setRequestHeader("Access-Control-Allow-Origin", "hello.html");
瀏覽器是Chrome
。我做錯了什麼或失蹤?
'Access-Control-Allow-Origin'標題需要在服務器端設置,而不是客戶端。您的後端使用什麼語言編寫? – AlliterativeAlice
@AlliterativeAlice紅寶石在Rails的 – cybertextron
對於本地解決跨起源問題,您可以安裝[允許控制允許原產地插件(https://chrome.google.com/webstore/detail/allow-control-allow -origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl = en) – sfletche