问题描述
我想在我的 Rails 应用程序中实现 CORS,所以我在谷歌上搜索了 rack-cors gem.我按照 README 中的说明做了所有事情,相应地更新了 Gemfile 并更新了 application.rb
,如下所示:
I wanted to implement CORS in my rails application, so I googled rack-cors gem for it. And I did everything as was said in README, that is updated Gemfile accordingly and updated application.rb
like this:
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.
But it didn't work. No matter what I did, in the browser console I kept getting message:XMLHttpRequest cannot load https://somewebsite.com. Origin http://0.0.0.0:3000 is not allowed by Access-Control-Allow-Origin.
阅读此 博文 和 issue 上,我意识到 rack-cors 中间件在中间件堆栈中的位置可能很重要.所以我按照github问题中的说明做了:
After reading this blogpost and issue on github, I realized that maybe position of rack-cors middleware in the middleware stack matters. So I did as was told in the github issue:
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 确实位于堆栈的顶部.
但它仍然根本行不通.我不断收到同样的错误.任何人,请帮忙.
After that, when I run rake middleware
rack-cors is really at the top of the stack.
But It still just simply won't work. I keep getting the same error. Anyone, please help.
推荐答案
我在使用 heroku 时遇到了同样的问题.我发现 this blog 有同样的 rack-cors 问题.
I ran into the same problem with heroku. I found this blog with the same rack-cors issue.
只需将 use Rack::Cors
移至 config.ru
,重新部署到 heroku 即可.
Just moved the use Rack::Cors
to config.ru
, redeployed to heroku and it works.
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
这篇关于无法让 rack-cors 在 rails 应用程序中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!