我想在我的rails应用程序中实现CORS,所以我为此搜索了rack-cors gem。我按照自述文件中的说明进行了所有操作,相应地更新了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 cannot load https://somewebsite.com. Origin http://0.0.0.0:3000 is not allowed by Access-Control-Allow-Origin.
在github上阅读了blogpost和issue之后,我意识到机架式中间件在中间件堆栈中的位置可能很重要。因此,我按照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具有相同的机架错误问题。
只需将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 - 无法在Rails应用程序中使用 Rack 芯,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18538549/