3

I'm using rack-cors to add the CORS response headers in our API requests.

It works fine when the requests succeeded (200). But when the application raises an exception ActiveRecord::RecordNotFound (404) or devise/invalid credentials through authenticate_user! (401) - it doesn't respond with the CORS response headers.

It isn't only with rack-cors. It doesn't respond with any custom header added before raising the exception.

The big problem is in the client side (browser), because instead of showing the proper error based on the status code, it shows:

XMLHttpRequest cannot load http://development.com:4000/orders/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://development.com:3000' is therefore not allowed access.

If I manually catch the exception rescue_from and render json: {}, status: 500 it responds with the headers.

Pablo Cantero
  • 6,239
  • 4
  • 33
  • 44

1 Answers1

5

I was fighting with that problem for long and the answer is:

the order in which you set the Rack::Cors middleware matters. Use it like this:

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do
  allow do
    origins '*'
    resource '*', headers: :any, methods: %i[get post patch put delete options]
  end
end

More info: https://github.com/cyu/rack-cors/issues/33

jtompl
  • 1,034
  • 13
  • 16