Skip to content

Instantly share code, notes, and snippets.

@nukturnal

nukturnal/my_api.rb

Forked from doitian/my_api.rb
Created Oct 19, 2015
Embed
What would you like to do?
Allow cors from any domain
class MyAPI < Grape::API
class CrossOriginResourceSharingPolicy < Grape::Middleware::Base
def append_cors_headers(headers)
headers['Access-Control-Allow-Origin'] = env['HTTP_ORIGIN'] || '*'
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '180'
if env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
headers['Access-Control-Allow-Headers'] = env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
end
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
end
def call!(env)
@env = env
append_cors_headers_for_error(catch(:error){
@app_response = @app.call(@env)
append_cors_headers @app_response[1]
return @app_response
})
end
def append_cors_headers_for_error(error = {})
error[:headers] ||= {}
append_cors_headers(error[:headers] ||= {})
# throw again to let Error middleware to handle it
throw :error, error
end
end
use CrossOriginResourceSharingPolicy
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment