Enable CORS in api rails

2

Using this GEM to enable CORS my application.

The code I have in my config/application.rb is as follows:

config.middleware.insert_before 0, 'Rack::Cors' do
  allow do
    origins 'http://localhost:8080'
    resource '*',
             headers: :any,
             methods: [:get, :post, :delete, :put, :options],
             max_age: 0
  end
end

The problem is that if I change anything in this configuration and restart the server the configuration does not apply.

Ex: If I remove : get and restart the server it was not to release cors for get but it keeps running as if it were there. What could it be?

    
asked by anonymous 02.06.2015 / 15:44

2 answers

1

I got to install this gem once and it also did not work for me. Doing some research on Google (I can not remember where I found it), I found a tutorial on how to configure CORS without a gem. In this case. just add some methods in application_controller.rb . It would look like this:

before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

protected

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST,DELETE, GET, PUT, PATCH, OPTIONS'
  headers['Access-Control-Allow-Headers'] = '*'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  if request.method == :options
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST,DELETE, GET, PUT, PATCH, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Max-Age'] = '1728000'
    render :text => '', :content_type => 'text/plain'
  end
end

I hope this helps.

    
18.06.2015 / 17:12
0

In my case I use Rails 5, I created a file called cors.rb in config / initializers / cors.rb

But I put it like this:

Rails.application.config.middleware.insert_before 0, "Rack::Cors", :debug => true, 
:logger => (-> { Rails.logger }) do  
  allow do
    origins '*'
    resource '*', 
        :headers => :any, 
        :methods => [:get, :post, :delete, :put, :patch, :options, :head]
    end
end

In my case, open my api

and in the wheel file, I added the name side of the resource so

resource :nome, :default => {format: :json}

And it worked for me, I had a lot of issues with CORS

    
20.11.2017 / 18:34