0

I seem to be running into some issues making a GET request to an API endpoint. I know rails has some security going on behind the scenes. I'm using React-Rails and in my componentDidMount to make an ajax call to an API endpoint. I am passing in a X-Auth-Token in my headers too.

My console error:

XMLHttpRequest cannot load "/api/end/point..." Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

My ajax call is looking like

$.ajax({ url: "my/api/endpoint...", headers: {"X-Auth-Token": "My API token..."},
    success: (response) => { console.log(response); } })
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
John
  • 3
  • 4

1 Answers1

0

Because your frontend will do requests from any origin (any client), you have to enable CORS from any origin. Try

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

I use this in a rails 5 api application. Before rails 5 add rack-cors gem to your Gemfile. Anyway, restart your server.

rails 3/4

# config/application.rb
module YourApp
  class Application < Rails::Application

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
  end
end
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • Thanks Ursus, I added the rack-cors gem and the code you described as above and still no luck. I also have my protect_from_forgery with: :null_session if that matters in my application_controller. Any ideas what else I might be doing wrong? – John Feb 27 '17 at 22:46
  • I updated my answer for rails 3/4. Try that and restart your server. – Ursus Feb 27 '17 at 22:52
  • I'm using rails 5, and tried both ways while restarting the server and still no luck. Im getting in the console: "XMLHttpRequest cannot load http://api/end/point...(my api endpoint) Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401." thanks! – John Feb 27 '17 at 23:03
  • It's very strange man. I have that config in so many rails 5 api application. I suppose you have restarted your server. – Ursus Feb 27 '17 at 23:06