Enable CORS in rails api

This using this GEM to enable the CORS of 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 something in this configuration and restart the server the configuration does not apply.

Ex: if I remove the : getand restart the server was not to be released the corsfor the get but it continues to work as if it were there. Why could it be?

Author: Guilherme Nascimento, 2015-06-02

2 answers

I got to install this gem once and it didn't work with me either. Doing some Google searches (I don't remember where I found it), I found a tutorial on how to set up 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.

 1
Author: Marco Damaceno, 2015-06-18 15:12:30

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

Which in my case my api

And in the wheels file, I added on the resource name side like so

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

And it worked for me, I had several problems with CORS

 0
Author: Antonio Ribeiro, 2017-11-20 17:34:52