Ruby-on-rails 通过 CORS 政策允许任何事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17858178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow anything through CORS Policy
提问by Nonconformist
How can I disable cors? For some reason I wild carded the allowed origins and headers yet my ajax requests still complain that the origin was not allowed by my CORS policy....
如何禁用cors?出于某种原因,我通配了允许的来源和标头,但我的 ajax 请求仍然抱怨我的 CORS 政策不允许该来源......
My applications controller :
我的应用程序控制器:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :current_user, :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-Allow-Headers'] = '*'
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
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
private
# get the user currently logged in
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
routes:
路线:
match "*all" => "application#cors_preflight_check", :constraints => { :method => "OPTIONS" }
match "/alert" => "alerts#create"
match "/alerts" => "alerts#get"
match "/login" => "sessions#create"
match "/logout" => "sessions#destroy"
match "/register" => "users#create"
Edit---
编辑 - -
I also tried:
我也试过:
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options]
end
end
in application.rb
在 application.rb 中
--edit 2---
--编辑2---
The problem is that Chrome Extensions may not support CORS I think. How can I fetch information bypassing CORS? How should I respond to the preflight check?
问题是我认为 Chrome 扩展可能不支持 CORS。如何绕过 CORS 获取信息?我应该如何应对飞行前检查?
回答by matteo
I've your same requirements on a public API for which I used rails-api.
我对使用 rails-api 的公共 API 有相同的要求。
I've also set header in a before filter. It looks like this:
我还在 before 过滤器中设置了标题。它看起来像这样:
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
It seems you missed the Access-Control-Request-Method header.
您似乎错过了 Access-Control-Request-Method 标头。
回答by Jef
回答by Abdallah Okasha
Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0
只需添加rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0
1st Step: add gem to your Gemfile:
第一步:将 gem 添加到您的 Gemfile 中:
gem 'rack-cors', :require => 'rack/cors'
and then save and run bundle install
然后保存并运行 bundle install
2nd Step: update your config/application.rb file by adding this:
第二步:通过添加以下内容来更新您的 config/application.rb 文件:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
for more details you can go to https://github.com/cyu/rack-corsSpecailly if you don't use rails 5.
有关更多详细信息, 如果您不使用 rails 5,您可以访问https://github.com/cyu/rack-cors特别地。
回答by Christoph Eicke
I had issues, especially with Chrome as well. What you did looks essentially like what I did in my application. The only difference is that I am responding with a correct hostnames in my Origin CORS headers and not a wildcard. It seems to me that Chrome is picky with this.
我遇到了问题,尤其是 Chrome。您所做的与我在应用程序中所做的基本相同。唯一的区别是我在 Origin CORS 标头中使用正确的主机名而不是通配符进行响应。在我看来,Chrome 对此很挑剔。
Switching between development and production is a pain, so I wrote this little function which helps me in development mode and also in production mode. All of the following things happen in my application_controller.rbunless otherwise noted, it might not be the best solution, but rack-corsdidn't work for me either, I can't remember why.
在开发和生产之间切换很痛苦,所以我写了这个小函数,它可以帮助我在开发模式和生产模式下。application_controller.rb除非另有说明,否则以下所有事情都发生在我的身上,这可能不是最好的解决方案,但rack-cors对我也不起作用,我不记得为什么。
def add_cors_headers
origin = request.headers["Origin"]
unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
origin = "https://your.production-site.org"
end
headers['Access-Control-Allow-Origin'] = origin
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
allow_headers = request.headers["Access-Control-Request-Headers"]
if allow_headers.nil?
#shouldn't happen, but better be safe
allow_headers = 'Origin, Authorization, Accept, Content-Type'
end
headers['Access-Control-Allow-Headers'] = allow_headers
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '1728000'
end
And then I have this little thing in my application_controller.rbbecause my site requires a login:
然后我有这个小东西,application_controller.rb因为我的网站需要登录:
before_filter :add_cors_headers
before_filter {authenticate_user! unless request.method == "OPTIONS"}
In my routes.rbI also have this thing:
在我的routes.rb我也有这个东西:
match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}
and this method looks like this:
这个方法看起来像这样:
def empty
render :nothing => true
end
回答by PropertyWebBuilder
I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.
我之前遇到过类似的问题,原来是网络浏览器(在我的情况下为 chrome)是问题所在。
If you are using chrome, try launching it so:
如果您使用的是 chrome,请尝试启动它:
For Windows:
对于 Windows:
1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.
1) 在桌面上创建 Chrome 的快捷方式。右键单击快捷方式并选择“属性”,然后切换到“快捷方式”选项卡。
2) In the “Target” field, append the following: –args –disable-web-security
2) 在“目标”字段中,附加以下内容:–args –disable-web-security
For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security
对于 Mac,打开一个终端窗口并从命令行运行它: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security
Above info from:
以上信息来自:
回答by H.B
Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.
刚刚在生产中的 Rails 应用程序中遇到了这个问题。这里的很多答案都给了我提示,并帮助我最终得出了一个对我有用的答案。
I am running Nginx and it was simple enough to just modify the my_app.conffile (where my_appis your app name). You can find this file in /etc/nginx/conf.d
我正在运行 Nginx,它很简单,只需修改my_app.conf文件(其中my_app是您的应用程序名称)。你可以在这个文件中找到/etc/nginx/conf.d
If you do not have location / {}already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*';under location / {}.
如果您还没有,则location / {}可以将其添加到 下server {},然后添加到add_header 'Access-Control-Allow-Origin' '*';下location / {}。
The final format should look something like this:
最终格式应如下所示:
server {
server_name ...;
listen ...;
root ...;
location / {
add_header 'Access-Control-Allow-Origin' '*';
}
}
回答by Leonardo Ostan
Try configuration at /config/application.rb:
在 /config/application.rb 尝试配置:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
end
end

