我在我的Rails 4应用程序中使用rack-cors gem,以便我可以执行基于JSON的API。我的项目中的所有GET方法工作正常,但POST方法返回500内部服务器错误。POST方法不能在机架轨道上工作4
我做的配置在我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' }
我已经尝试了大部分的堆栈溢出解决方案,但它没有帮助。任何人都可以请帮我在这里。
您是否试过rails-api gem? –