我想在我的 Rails 应用程序中实现 CORS,所以我用谷歌搜索了 rack-cors gem 吧。我按照 README 中所说的做了所有事情,相应地更新了 Gemfile 并像这样更新了 application.rb
:
module YourApp
class Application < Rails::Application
# ...
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
但是没有用。无论我做什么,在浏览器控制台中我都不断收到消息:
XMLHttpRequest 无法加载 https://somewebsite.com。 Access-Control-Allow-Origin 不允许来源 http://0.0.0.0:3000。
看完这篇blogpost和 issue在 github 上,我意识到 rack-cors 中间件在中间件堆栈中的位置可能很重要。所以我按照 github 问题中的说明做了:
module YourApp
class Application < Rails::Application
# ...
config.middleware.insert 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
在那之后,当我运行 rake middleware
时,rack-cors 确实位于堆栈的顶部。
但它仍然只是行不通。我不断收到同样的错误。任何人,请帮助。
最佳答案
我在 heroku 上遇到了同样的问题。我找到了 this blog具有相同的 rack-cors 问题。
刚刚将 use Rack::Cors
移动到 config.ru
,重新部署到 heroku,它就可以工作了。
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
require 'rack/cors'
use Rack::Cors do
# allow all origins in development
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options]
end
end
关于ruby-on-rails - 无法让 rack-cors 在 rails 应用程序中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18538549/