Skip to content

Instantly share code, notes, and snippets.

@crwang
Created November 25, 2014 08:14
Show Gist options
  • Save crwang/4cd885f931e0f24b48c2 to your computer and use it in GitHub Desktop.
Save crwang/4cd885f931e0f24b48c2 to your computer and use it in GitHub Desktop.
Cross Origin Rails 4 API Controller
module Api::V1
# Subclass from our normal api controller base class.
class CrossSiteController < ApiController
after_filter :cors_set_access_control_headers
def route_options
cors_preflight_check
end
private
def cors_set_access_control_headers
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token, Auth-Token, Email'
response.headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == 'OPTIONS'
request.headers['Access-Control-Allow-Origin'] = '*'
request.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS'
request.headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token, Auth-Token, Email'
request.headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
end
end
module Api::V1
class CustomEventsController < CrossSiteController
def create
# Implementation here
render json: {}
end
end
end
Rails.application.routes.draw do
root 'main#index'
concern :api_routes do
post 'events' => "events#create"
end
scope :api, module: "api/v1", defaults: {format: :json} do
concerns :api_routes
end
controller 'api/v1/cross_site' do
match '*unmatched_route', :to => 'api/v1/cross_site#route_options', via: [:options]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment