-
-
Save wiserfirst/db902e58ccd756ccc019 to your computer and use it in GitHub Desktop.
CORS in Rails 4 APIs
This file contains hidden or 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
| class Api::BaseController < ActionController::Base | |
| protect_from_forgery with: :null_session | |
| before_action :authenticate, :except => [:preflight_check] | |
| after_action :cors_set_access_control_headers | |
| def preflight_check | |
| if request.method == 'OPTIONS' | |
| render :text => '', :content_type => 'text/plain' | |
| end | |
| end | |
| private | |
| def authenticate | |
| # implement your authentication method | |
| raise 'You need to implement authenticate()' | |
| end | |
| def cors_set_access_control_headers | |
| headers['Access-Control-Allow-Origin'] = '*' | |
| headers['Access-Control-Allow-Methods'] = 'POST, PATCH, DELETE, OPTIONS' | |
| headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, X-Prototype-Version, Token' | |
| headers['Access-Control-Max-Age'] = '1728000' | |
| end | |
| end |
This file contains hidden or 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
| Rails.application.routes.draw do | |
| namespace :api, :defaults => {:format => :json} do | |
| resources :whatever, :another | |
| # for the preflight request | |
| match "*path" => "base#preflight_check", via: [:options] | |
| end | |
| end |
This file contains hidden or 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
| class Api::WhateverController < Api::BaseController | |
| def upload | |
| # Do complicated super secret stuff | |
| render json: { success: true } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment