I'm trying to call an endpoint(POST
https://target-endpoint.com/authentication
) from another origin(https://origin.com
) with below header settings, but CORS error has remain raised.
Is there any mistake in my settings?
authentications_controller.rb
def create
response.headers['access-control-allow-origin'] = 'https://origin.com'
// some impl
end
routes.rb
Rails.application.routes.draw do
post :authentication, to: "authentications#create", via: :options
end
error in chrome console
Access to fetch at 'https://target-endpoint.com/authentication' from origin 'https://origin.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
If you have any idea, please let me know. Thanks,
other conds.
- heroku, with stack 18
- ruby 2.6.4
- rails 6.0.4.8
CodePudding user response:
Before browsers make a cross-origin POST request, they first perform a so called CORS-preflight request to make sure that the target of the POST allows the request.
For that, browsers make an OPTIONS
request to the URL and check the CORS headers of the response. Only if the respone headers of this preflight request indicate that the request is allowed, browsers will perform the actual POST
request.
For you, that means that your create
action (for the POST
request) won't receive a request unless you also reply to an OPTIONS
request first.
While you could implement this "by hand", it is usually a much better idea to use existing CORS implementation such as the rack-cors
gem.