我对使用rails-api的公共API有相同的要求。
我还在前一个过滤器中设置了标题。它看起来像这样:
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'
您似乎错过了Access-Control-Request-Method标头。
我遇到了问题,尤其是Chrome。你做的看起来基本上就像我在我的应用程序中所做的那样。唯一的区别是我在Origin CORS标头中使用正确的主机名而不是通配符。在我看来,Chrome对此很挑剔。
在开发和生产之间切换是一件痛苦的事情,所以我写了这个小功能,这有助于我在开发模式和生产模式。以下所有事情都发生在我的身上 application_controller.rb 除非另有说明,否则它可能不是最佳解决方案,但是 机架CORS 也不适合我,我不记得为什么。
application_controller.rb
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
然后我在我的这个小东西 application_controller.rb 因为我的网站需要登录:
before_filter :add_cors_headers before_filter {authenticate_user! unless request.method == "OPTIONS"}
在我的 routes.rb 我也有这个东西:
routes.rb
match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}
这个方法看起来像这样:
def empty render :nothing => true end
我之前遇到过类似的问题,结果就是网页浏览器(我的情况下是chrome)。
如果您使用的是chrome,请尝试启动它:
对于Windows:
1)在桌面上创建Chrome的快捷方式。右键单击快捷方式并选择“属性”,然后切换到“快捷方式”选项卡。
2)在“目标”字段中,附加以下内容:锟绀args锟绀disable-web-security
对于Mac,打开终端窗口并从命令行运行: 打开〜/ Applications / Google \ Chrome.app/锟绀args锟绀disable-web-security
以上信息来自:
http://documentumcookbook.wordpress.com/2012/03/13/disable-cross-domain-javascript-security-in-chrome-for-development/
看看吧 机架CORS 中间件。它将以可配置的方式处理CORS头。
刚刚在我的rails应用程序中遇到这个问题。这里有很多答案给了我一些提示并帮助我最终找到了一个对我来说很好的答案。
我正在运行Nginx,它很简单,只需修改 my_app.conf 文件(在哪里 my_app应用 是你的应用名称)。你可以找到这个文件 /etc/nginx/conf.d
/etc/nginx/conf.d
如果你没有 location / {} 你已经可以添加它了 server {} , 然后加 add_header 'Access-Control-Allow-Origin' '*'; 下 location / {} 。
location / {}
server {}
add_header 'Access-Control-Allow-Origin' '*';
最终格式应如下所示:
server { server_name ...; listen ...; root ...; location / { add_header 'Access-Control-Allow-Origin' '*'; } }
尝试在/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