Skip to content

Instantly share code, notes, and snippets.

@locnguyen
Last active December 31, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save locnguyen/7998611 to your computer and use it in GitHub Desktop.
Save locnguyen/7998611 to your computer and use it in GitHub Desktop.
This is how I enable CORS in a Rails 4 application. The app is a JSON API consumed by an AngularJS front-end. Still a work in progress...
# Add a preflight check method and a set headers methond in ApplicationController
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
before_filter :set_cors_headers
before_filter :cors_preflight_check
def set_cors_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE,OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '3628800'
end
def cors_preflight_check
head(:ok) if request.method == 'OPTIONS'
end
end
# Configure routes.rb to allow requests to any path with the OPTIONS verb.
Corsware::Application.routes.draw do
match '*all' => 'application#cors_preflight_check', :constraints => { :method => 'OPTIONS' }, via: [:options]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment