Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CORS in Rails 4 APIs
class API::V1::BaseController < ApplicationController
skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == 'OPTIONS'
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
end
Rails.application.routes.draw do
namespace :api, :defaults => {:format => :json} do
namespace :v1 do
controller :whatever, path: '/whatever' do
match 'post_action', via: [ :post, :options]
end
end
end
end
class API::V1::WhateverController < API::V1::BaseController
def upload
# Do complicated super secret stuff
render json: { success: true }
end
end
@robinschaaf

This comment has been minimized.

Show comment Hide comment
@robinschaaf

robinschaaf Jan 3, 2015

Thanks so much for posting this.
Just a little note in case anyone has the problem, I was performing post using Angular's $http.post, and needed to add 'content-type' to the allowed headers on the preflight check, I guess since angular's post always automagically adds json as the content type. Otherwise this worked like a charm!

Thanks so much for posting this.
Just a little note in case anyone has the problem, I was performing post using Angular's $http.post, and needed to add 'content-type' to the allowed headers on the preflight check, I guess since angular's post always automagically adds json as the content type. Otherwise this worked like a charm!

@sebastialonso

This comment has been minimized.

Show comment Hide comment
@sebastialonso

sebastialonso Mar 4, 2015

Thanks for the gist!

I have an issue though. It seems that the OPTION request worked, because I get 200 OK from my Angular app. But that's all I get, I don't get any response with the data I need.

Any idea how to solve this?

Thanks for the gist!

I have an issue though. It seems that the OPTION request worked, because I get 200 OK from my Angular app. But that's all I get, I don't get any response with the data I need.

Any idea how to solve this?

@Braidio

This comment has been minimized.

Show comment Hide comment
@Braidio

Braidio Apr 17, 2015

@sebastialonso Same here. Any luck with that?

Braidio commented Apr 17, 2015

@sebastialonso Same here. Any luck with that?

@pasupulaphani

This comment has been minimized.

Show comment Hide comment
@pasupulaphani

pasupulaphani Apr 28, 2015

@sebastialonso , Please have a look at line 22

render :text => ''

Change the above to send same response to all Options reqs. You can extend this by setting a necessary handler instead of render.

@sebastialonso , Please have a look at line 22

render :text => ''

Change the above to send same response to all Options reqs. You can extend this by setting a necessary handler instead of render.

@jnwelzel

This comment has been minimized.

Show comment Hide comment
@jnwelzel

jnwelzel May 4, 2015

So you're basically all-round disabling the same-origin policy?

jnwelzel commented May 4, 2015

So you're basically all-round disabling the same-origin policy?

@urbanvikingr

This comment has been minimized.

Show comment Hide comment
@urbanvikingr

urbanvikingr Jun 26, 2015

I'm getting this error:

XMLHttpRequest cannot load http://localhost:3000/api/auth/google_oauth2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Any suggestions?

I'm getting this error:

XMLHttpRequest cannot load http://localhost:3000/api/auth/google_oauth2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Any suggestions?

@ekyfauzi

This comment has been minimized.

Show comment Hide comment
@ekyfauzi

ekyfauzi Sep 10, 2015

I have same error like @urbanvikingr
I'm use Rails 4 for backend and Angular for the frontend

Please help :(

I have same error like @urbanvikingr
I'm use Rails 4 for backend and Angular for the frontend

Please help :(

@ekyfauzi

This comment has been minimized.

Show comment Hide comment
@ekyfauzi

ekyfauzi Sep 10, 2015

Hi, finally I solve the problem
the problem is in my Rails app

I found this:
https://github.com/cyu/rack-cors

@urbanvikingr I hope it can solve your problem too

Hi, finally I solve the problem
the problem is in my Rails app

I found this:
https://github.com/cyu/rack-cors

@urbanvikingr I hope it can solve your problem too

@snappa

This comment has been minimized.

Show comment Hide comment
@snappa

snappa Sep 17, 2015

Wow, thank you so much! This helped me over the hurdle testing my ionic app. I know I have some tweaking to get this dialed in just right but this was immensely helpful!

snappa commented Sep 17, 2015

Wow, thank you so much! This helped me over the hurdle testing my ionic app. I know I have some tweaking to get this dialed in just right but this was immensely helpful!

@jmillman

This comment has been minimized.

Show comment Hide comment
@jmillman

jmillman Sep 22, 2015

How can you do this with the assets pipeline?

How can you do this with the assets pipeline?

@panchew

This comment has been minimized.

Show comment Hide comment
@panchew

panchew Oct 10, 2015

Thank you very much for posting this.
It worked perfectly for me.

panchew commented Oct 10, 2015

Thank you very much for posting this.
It worked perfectly for me.

@npetkov

This comment has been minimized.

Show comment Hide comment
@npetkov

npetkov Feb 24, 2016

Just in case someone stumbles upon this gist, here's a more brief solution to the problem.

  1. Tell rails (rack) what to do with OPTIONS requests:

    Append this simple line to the end of your routes.rb file:

      match '*path', via: [:options], to:  lambda {|_| [204, {'Content-Type' => 'text/plain'}, []]}

    What does it do? It will handle OPTIONS requests on all of your routes, responding with no content and the appropriate Access-Control headers. The response is rendered on rack level, so you won't have to think about this on higher levels (e.g. controllers).

  2. Add the headers you need via rack-cors:

    You can insert this snippet in environments/development.rb.

    config.middleware.insert_before 0, 'Rack::Cors', logger: (-> { Rails.logger }) do
      allow do
        origins 'localhost:3000'
    
        resource '*',
          headers: :any,
          methods: [:get, :post, :delete, :put, :patch, :options, :head],
          max_age: 0
      end
    end

    That's it really.

npetkov commented Feb 24, 2016

Just in case someone stumbles upon this gist, here's a more brief solution to the problem.

  1. Tell rails (rack) what to do with OPTIONS requests:

    Append this simple line to the end of your routes.rb file:

      match '*path', via: [:options], to:  lambda {|_| [204, {'Content-Type' => 'text/plain'}, []]}

    What does it do? It will handle OPTIONS requests on all of your routes, responding with no content and the appropriate Access-Control headers. The response is rendered on rack level, so you won't have to think about this on higher levels (e.g. controllers).

  2. Add the headers you need via rack-cors:

    You can insert this snippet in environments/development.rb.

    config.middleware.insert_before 0, 'Rack::Cors', logger: (-> { Rails.logger }) do
      allow do
        origins 'localhost:3000'
    
        resource '*',
          headers: :any,
          methods: [:get, :post, :delete, :put, :patch, :options, :head],
          max_age: 0
      end
    end

    That's it really.

@gabamnml

This comment has been minimized.

Show comment Hide comment
@gabamnml

gabamnml Mar 18, 2016

Awesome! thanks.

Awesome! thanks.

@MartinKei

This comment has been minimized.

Show comment Hide comment
@MartinKei

MartinKei Jun 15, 2016

@npetkov - thank you very much!

@npetkov - thank you very much!

@nshoes

This comment has been minimized.

Show comment Hide comment
@nshoes

nshoes Jul 20, 2016

@npetkov - 👍

nshoes commented Jul 20, 2016

@npetkov - 👍

@davidcotter

This comment has been minimized.

Show comment Hide comment
@davidcotter

davidcotter Aug 24, 2016

@npetkov - thanks! For the first part I added this to routes and it got everything working:

 Rails.application.routes.draw do
   ...
   match '*path', via: [:options], to:  lambda {|_| [204, {'Access-Control-Allow-Headers' => "Origin, Content-Type, Accept, Authorization, Token", 'Access-Control-Allow-Origin' => "*", 'Content-Type' => 'text/plain'}, []]}
end

That solved the problem. What is the second part for

@npetkov - thanks! For the first part I added this to routes and it got everything working:

 Rails.application.routes.draw do
   ...
   match '*path', via: [:options], to:  lambda {|_| [204, {'Access-Control-Allow-Headers' => "Origin, Content-Type, Accept, Authorization, Token", 'Access-Control-Allow-Origin' => "*", 'Content-Type' => 'text/plain'}, []]}
end

That solved the problem. What is the second part for

@cesc1989

This comment has been minimized.

Show comment Hide comment
@cesc1989

cesc1989 Dec 6, 2016

Thanks a lot @npetkov

And thank you @davidcotter too

cesc1989 commented Dec 6, 2016

Thanks a lot @npetkov

And thank you @davidcotter too

@aymericbouzy

This comment has been minimized.

Show comment Hide comment
@aymericbouzy

aymericbouzy Jan 12, 2017

I opened an issue for that rails/rails#27655

I opened an issue for that rails/rails#27655

@wellington1993

This comment has been minimized.

Show comment Hide comment
@wellington1993

wellington1993 Jan 19, 2017

Thanks

Thanks

@jarrettgreen

This comment has been minimized.

Show comment Hide comment
@jarrettgreen

jarrettgreen May 9, 2017

I get a Rack lint error when trying to pass any headers with a 204.

I get a Rack lint error when trying to pass any headers with a 204.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment