Last active
December 31, 2015 14:09
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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