Wag*_*sUK 21 ruby ajax ruby-on-rails cors ruby-on-rails-4
我正要把我的头发拉出来...我从早上起就试图在这个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();
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这个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
Run Code Online (Sandbox Code Playgroud)
apn*_*ing 36
你应该使用机架式的
它提供了一个很好的DSL,用于你的config/application.rb,而不是凌乱的标题工作和过滤器之前.
一个非常宽容的将如下,但当然,你将不得不量身定制它.
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :any
end
end
Run Code Online (Sandbox Code Playgroud)
err*_*hpd 13
Rack :: Cors为跨源资源共享提供支持
启用rackcors的步骤:
1.添加宝石到你的Gemfile:
gem 'rack-cors'
Run Code Online (Sandbox Code Playgroud)
2.将以下代码添加到config/application.rb
# if you are using Rails 3/4
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => :any
end
end
# if you are using Rails 5
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :any
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19797 次 |
| 最近记录: |