【发布时间】:2015-06-27 08:51:34
【问题描述】:
我正要拔掉头发...从早上开始,我一直在尝试在这个 Rails 应用程序中启用 CORS,但它不起作用。我试过this、使用Rack Cors Gem、this answer和这个post都没有成功。
有人能指出正确的方向吗?
这是我的 js:
var req = new XMLHttpRequest();
if ('withCredentials' in req) {
// req.open('GET', "https://api.github.com/users/mralexgray/repos", true);
req.open('GET', "http://www.postcoder.lc/postcodes/" + value, true);
// Just like regular ol' XHR
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status >= 200 && req.status < 400) {
// JSON.parse(req.responseText) etc.
console.log(req.responseText);
} else {
// Handle error case
}
}
};
req.send();
}
当我尝试这个 url(来自外部客户端):https://api.github.com/users/mralexgray/repos 工作正常时,我假设问题出在我的 Rails API 上。我错了吗?
编辑:目前我的控制器中有这个:
skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
# For all responses in this controller, return the CORS access control headers.
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = "1728000"
end
# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.
def cors_preflight_check
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
headers['Access-Control-Max-Age'] = '1728000'
end
【问题讨论】:
-
我试过了,没用。我什至使用了示例应用程序,但仍然没有运气
-
你曾经得到这个工作?我有一个有角度的前端打电话,我也尝试了所有的解决方案。 rack cors gem 对我不起作用。
标签: ruby-on-rails ruby ajax ruby-on-rails-4 cors