How to save response headers when creating an exception?

I use rack-cors to add CORS response headers to our API requests.

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

It is not only racks. It does not respond with the addition of any custom header before raising the exception.

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

XMLHttpRequest cannot load http://development.com:4000/orders/1 . The requested resource does not have an Access-Control-Allow-Origin header. The origin of http://development.com//000 'is therefore not allowed.

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

+3
source share
1 answer

I struggled with this problem for a long time, and the answer is:

the order in which you install the Rack :: Cors middleware. 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

Additional information: https://github.com/cyu/rack-cors/issues/33

+5
source

All Articles