-
-
Save luisguzman02/293e4a135d9b61d0cd28cf6ebd924c0e 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::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 |
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 | |
| namespace :v1 do | |
| controller :whatever, path: '/whatever' do | |
| match 'post_action', via: [ :post, :options] | |
| end | |
| end | |
| 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::V1::WhateverController < API::V1::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