samedi 10 octobre 2015

POST Method not working in rack-cors rails 4

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.

Aucun commentaire:

Enregistrer un commentaire