Ember+Rails devs: what do you do for CORS/OPTIONS responses?

Hi all,

I’m researching into what folks are using for handling CORS with their Rails+Ember apps and would love to read what you’ve done and liked/not liked!

Many thanks,

Eliot

I’m using the cors gem on the ruby side.

On the ember side I have

Ember.$.ajaxSetup(
  crossDomain: true
)

I found out later I could probably avoid the whole thing by using the --proxy option on ember-cli as long as you don’t need cors in the live env.

2 Likes

@varblob Was this the gem? https://github.com/cyu/rack-cors There is also a cors gem that I think might be tied to use with Amazon S3.

My apologies, I should have included

# cross origin policy rack middleware
gem 'rack-cors', require: 'rack/cors'

and here is what my cors initializer looks like

Rails.application.config.middleware.insert_before 0, "Rack::Cors", debug: true, logger: (-> { Rails.logger }) do
  allow do
    origins 'originoftheemberapp', 'anotheremberapporigin'

    resource '*',
      headers: :any,
      methods: [:get, :post, :delete, :put, :options, :head],
      credentials: true,
      max_age: 0
  end
end

Let me know if that does it for you. I think I picked out the important bits but I maybe missing something. This is also assuming you’re not using cookies for auth. If you are then you need to also include

Ember.$.ajaxSetup(
  crossDomain: true
  xhrFields:
    withCredentials: true <-- this bit
)

and I think you need this too but it maybe redundant

ApplicationAdapter = DS.ActiveModelAdapter.extend(
  corsWithCredentials: true <-- this bit
)

If you’re using devise cookie based sessions and ember-simple-auth this may also be interesting WARNING this is not the default way to use simple-auth and devise

1 Like

Thanks for the awesome answer @varblob :smiley:

@eliotsykes

I realize I didn’t note that cookie based auth for devise with ember-simple-auth is not the default way. ember-simple-auth uses token based authentication by default.

it’s all :slight_smile:

    if request.headers["HTTP_ORIGIN"]
      headers['Access-Control-Allow-Origin']       = '*'
      headers['Access-Control-Expose-Headers']     = 'ETag'
      headers['Access-Control-Allow-Methods']      = 'GET, POST, PUT, DELETE, OPTIONS, HEAD'
      headers['Access-Control-Allow-Headers']      = 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token'
    end

It is not working for me. It works for the GET method but when I try to update a Ember Model into the Rails backend, the first request that Ember does is a OPTIONS request and looks like the rack-cors is not managing this request because I’m receiving a No route matches [OPTIONS] error.

I don’t know what I’m missing, I have open a bug report in the rack-cors repo.