POST方法无法在机架轨道中工作4
我在我的Rails 4应用程序中使用rack-cors gem,这样我就可以使用基于JSON的API。 我项目中的所有GET方法都运行正常,但POST方法返回500内部服务器错误。
我正在我的application.rb
文件中进行配置,如下所示:
module Railsapp class Application :any, :methods => [:get, :post, :put, :options, :delete] end end end end
我的application_controller.rb
文件如下所示:
before_filter :cors_preflight_check after_filter :cors_set_access_control_headers 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 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
在routes.rb
文件中,我添加了这一行
get '*all' => 'application#cors_preflight_check', :constraints => { :method => 'OPTIONS' }
我已经尝试了大多数stackoverflow解决方案,但它没有帮助。 有人可以帮帮我吗。
好的,如果您使用的是rack-cors
gem,则不必在application_controller
和routes
包含cors_*
方法
application.rb
的代码就足够了。 但是,如果您仍然看到问题,请尝试查看gem的rails4应用程序的示例项目: https : //github.com/cyu/rack-cors/blob/master/examples/rails4/
https://github.com/cyu/rack-cors/blob/master/lib/rack/cors.rb#L306
当你没有设置false选项时,rack-cors使用’Access-Control-Allow-Credentials’= true。
因此,当credentials标志为true时,您不能在’Access-Control-Allow-Origin’中使用通配符。 如果你想使用通配符,写这样的。
allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false end