对这个问题的工作页面,我写了下面的脚本:发布使用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