jadent
jadent

Reputation: 3904

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

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.

Upvotes: 3

Views: 1085

Answers (1)

skatkov
skatkov

Reputation: 133

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

Upvotes: 1

Related Questions