我快要抓狂了...自早上以来,我一直在尝试在这个Rails应用程序中启用CORS,但它就是不起作用。我已经尝试过 这个、使用 Rack Cors Gem、这个答案 和这篇 文章,但都没有成功。
有人可以指点我正确的方向吗?
这是我的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