-
-
Save nukturnal/bbe2e4bad0d9bfda7f40 to your computer and use it in GitHub Desktop.
Allow cors from any domain
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
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