2

I am using rack-cors gem with my Rails 4 application so that I can do a JSON based API. All the GET method in my project is working fine, but POST method returns 500 internal server error.

I am doing the configuration in my application.rb file like this:

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

My application_controller.rb file looks like this:

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

In routes.rb file I have added this line

  get '*all' => 'application#cors_preflight_check', :constraints => { :method => 'OPTIONS' }

I have tried most of the stackoverflow solutions, but it doesn't help. Can anyone please help me out here.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
saravana
  • 311
  • 4
  • 14

2 Answers2

0

Ok so if you are using the rack-cors gem you don't have to include the cors_* methods on your application_controller and routes

The code in your application.rb is enough. However if you still see problems, try looking at the example project of a rails4 application of the gem: https://github.com/cyu/rack-cors/blob/master/examples/rails4/

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
0

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

rack-cors use 'Access-Control-Allow-Credentials' = true, when you not set false option.

So, when credentials flag is true, you cannot use wildcard in 'Access-Control-Allow-Origin'. if you want to use wildcard, write like this.

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