【发布时间】:2015-05-09 01:45:45
【问题描述】:
为了解决这个问题,我编写了以下脚本:
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 Ruby 在 Rails 中
-
对于跨源问题的本地解决方案,您可以安装Allow-Control-Allow-Origin plugin
-
@sfletche 任何程序化解决方案?
-
没有简单的编程解决方案...
标签: javascript ruby-on-rails json http post