問(wèn)題描述
我正要拔掉頭發(fā)...從早上開始,我一直在嘗試在這個(gè) Rails 應(yīng)用程序中啟用 CORS,但它不起作用.我試過(guò) this,使用 Rack Cors Gem, 這個(gè)答案和這個(gè)post都沒(méi)有成功.
I'm just about to pull my hair out... I've been trying to enable CORS in this Rails app since the morning and it just doesn't work. I've tried this, using Rack Cors Gem, this answer and this post all without success.
有人能指出正確的方向嗎?
Can someone point me in the right direction?
這是我的 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();
}
當(dāng)我嘗試這個(gè)網(wǎng)址時(shí)(來(lái)自外部客戶端):https://api.github.com/users/mralexgray/repos 工作正常,我假設(shè)問(wèn)題出在我的 Rails API 上.我錯(cuò)了嗎?
When I try this url (from an external client): https://api.github.com/users/mralexgray/repos that works ok, I'm assuming the problem is with my Rails API. Am I wrong?
目前我的控制器中有這個(gè):
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
推薦答案
你應(yīng)該使用 rack cors
它提供了一個(gè)很好的 DSL,可以在你的 config/application.rb
中使用,而不是在過(guò)濾器之前使用凌亂的標(biāo)題.
It provides a nice DSL, to use in your config/application.rb
, instead of the messy header work and before filters.
一個(gè)非常寬松的方法如下,但當(dāng)然,你必須稍微調(diào)整一下.
A very permissive would be as follows, but of course, you'll have to tailor it a bit.
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :any
end
end
這篇關(guān)于如何在 Rails 4 應(yīng)用程序中啟用 CORS的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!