So aktivieren Sie CORS in der Rails 4-App
Ich bin gerade dabei, mir die Haare auszureißen ... Ich habe seit dem Morgen versucht, CORS in dieser Rails-App zu aktivieren, und es funktioniert einfach nicht. Ich habe es versuchtDie mitRack Cors Gem, diese Antwort und dasPos alles ohne erfolg.
Kann mich jemand in die richtige Richtung weisen?
Hier ist mein 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();
}
Wenn ich diese URL ausprobiere (von einem externen Client):https: //api.github.com/users/mralexgray/repo das funktioniert ok, ich gehe davon aus, dass das Problem mit meiner Rails-API ist. Liege ich falsch
EDIT: Derzeit habe ich dies in meinem Controller:
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