Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rack-cors gem and setting Access-Control-Allow-Origin Header

Tags:

cors

rack

Is there a way to set the "Access-Control-Allow-Origin" header value when using the rack-cors gem?

We're using the rack-cors gem https://github.com/cyu/rack-cors to manage CORS for Grape app.

I want to send back a permanent redirect and redirect them off the current subdomain to another subdomain. The Grape code is:

redirect 'subdomain2.oursite.com, 'Access-Control-Allow-Origin' => '*',permanent: true 

But this won't work as the rack-cors overwrites the Access-Control-Allow-Origin header value with the current URL that the request is coming in on which causes a CORS preflight error.

So need a way to set the value.

like image 498
jadent Avatar asked Dec 04 '25 01:12

jadent


1 Answers

I had a similar problem with my API and stumbled upon this question here. While there is no active solution provided, I managed to find one that worked for me.

class Api::BaseController < ActionController::API
  respond_to :json
  before_filter :set_cors_header
  after_filter :cors_set_access_control_headers

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  end

  def set_cors_header
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Typee, Accept, Authorization'
  end
end
like image 91
skatkov Avatar answered Dec 06 '25 19:12

skatkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!