Enable CORS in api Rails

Asked

Viewed 1,232 times

3

They’re using this one 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 :get and restarting the server was not to be released the Cors to the get but it continues to function as if it were there. What could be?

  • You are following this example? see that it is possible to enable debug and see on the logger how CORS is being treated

2 answers

1

I once installed that Gem and it didn’t work for me either. Doing some Google searches (I can’t remember where I found), I found a tutorial on how to configure CORS without a Gem. In this case. simply add some methods to the application_controller.rb. Would that be:

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.

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

that in my case is opened my api

and in the wheel file, I added the Resource name side like this

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

and it worked for me, I had several problems with the CORS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.