Last active
November 19, 2021 16:00
-
-
Save jpbalarini/54a1aa22ebb261af9d8bfd9a24e811f0 to your computer and use it in GitHub Desktop.
Ruby on Rails CORS Preflight Check
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
before_action :cors_set_access_control_headers | |
def cors_preflight_check | |
return unless request.method == 'OPTIONS' | |
cors_set_access_control_headers | |
render json: {} | |
end | |
protected | |
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, X-User-Token, X-User-Email, x-xsrf-token' | |
response.headers['Access-Control-Max-Age'] = '1728000' | |
response.headers['Access-Control-Allow-Credentials'] = true | |
end |
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
match '*all', controller: 'application', action: 'cors_preflight_check', via: [:options] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To anyone still relying on this and the Medium post, the "correct" way to render the response is now
head :no_content
(notice there is no render).