Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow CORS in Ruby on Rails

In my config/application.rb file, I have this code,

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => 'GET, PATCH, PUT, POST, OPTIONS, DELETE'
    }

But that does not allow me to send a post request to a route on my sever

Safari gives this error:

http://localhost:3000/studentsFailed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/studentsFailed to load resource: Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origin.
localhost:1XMLHttpRequest cannot load http://localhost:3000/students. Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origi

And in my Rails server console:

Started OPTIONS "/students" for ::1 at 2015-03-28 21:00:45 -0500

ActionController::RoutingError (No route matches [OPTIONS] "/students"):
like image 343
Ben Aubin Avatar asked Mar 29 '15 02:03

Ben Aubin


People also ask

How do I enable CORS in rails?

Using rack-cors You need to inform Rails which origin it should allow. To do that, you need to create a new initializer for your application. This configuration will only allow HTTP POST calls to /order endpoint and all HTTP methods to any other endpoint. You need to pay close attention to the origins parameter.

How do you fix the CORS error in Ruby?

Fixing the “CORS” errorAdd the rack-cors gem to Gemfile and bundle install . Then open the file at config/initializers/cors. rb . You'll see that it's completely commented out at first.

How do I enable CORS access?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.

How do you fix CORS missing Allow origin?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

I spent some time working on this and I can tell you the most reliable solution is to use rack-cors. see: https://github.com/cyu/rack-cors

First add the gem:

gem 'rack-cors', '~> 0.3.1'

then in application.rb add

config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

If your production app does not serve static assets (such as if you use a serve like nginx or apache), consider replacing ActionDispatch::Static in the above example with 0. See https://github.com/cyu/rack-cors#common-gotchas for more information about the argument.

like image 182
errata Avatar answered Sep 18 '22 16:09

errata