【问题标题】:POST Method not working in rack-cors rails 4POST 方法在机架导轨中不起作用 4
【发布时间】:2016-01-08 06:46:00
【问题描述】:

我在我的 Rails 4 应用程序中使用 rack-cors gem,这样我就可以做一个基于 JSON 的 API。我项目中的所有 GET 方法都工作正常,但是 POST 方法返回 500 内部服务器错误。

我正在我的application.rb 文件中进行配置,如下所示:

module Railsapp
class Application < Rails::Application    
  config.active_record.raise_in_transactional_callbacks = true
  config.middleware.insert_before 0, "Rack::Cors" do
    allow do
      origins '*'
      resource '*', :headers => :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 解决方案,但都没有帮助。谁能帮帮我。

【问题讨论】:

  • 你试过 rails-api gem 吗?

标签: ruby-on-rails ruby


【解决方案1】:

好的,如果您使用的是rack-cors gem,则不必在您的application_controllerroutes 中包含cors_* 方法

application.rb 中的代码就足够了。但是,如果您仍然发现问题,请尝试查看 gem 的 rails4 应用程序示例项目:https://github.com/cyu/rack-cors/blob/master/examples/rails4/

【讨论】:

    【解决方案2】:

    https://github.com/cyu/rack-cors/blob/master/lib/rack/cors.rb#L306

    rack-cors 使用 'Access-Control-Allow-Credentials' = true,当您没有设置 false 选项时。

    因此,当凭据标志为真时,您不能在“Access-Control-Allow-Origin”中使用通配符。如果你想使用通配符,这样写。

    allow do
      origins '*'
      resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
    end
    

    【讨论】:

      猜你喜欢
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 2017-01-28
      • 1970-01-01
      相关资源
      最近更新 更多