Skip to content

Instantly share code, notes, and snippets.

Embed
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
@MartinKei
Copy link

MartinKei commented Jun 15, 2016

@npetkov - thank you very much!

@nshoes
Copy link

nshoes commented Jul 20, 2016

@npetkov - 👍

@davidcotter
Copy link

davidcotter commented 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

@cesc1989
Copy link

cesc1989 commented Dec 6, 2016

Thanks a lot @npetkov

And thank you @davidcotter too

@aymericbouzy
Copy link

aymericbouzy commented Jan 12, 2017

I opened an issue for that rails/rails#27655

@wellington1993
Copy link

wellington1993 commented Jan 19, 2017

Thanks

@jarrettgreen
Copy link

jarrettgreen commented May 9, 2017

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

@jpmagido
Copy link

jpmagido commented Nov 23, 2020

Nice, you made my day ^^

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