How to add Access-Control-Allow-Origin headers to API Response in Ruby
Sinatra is a simple and lightweight web server. The general idea is that you write response routes like this:
get '/api' do
"Hello world"
end
When you make a HTTP GET request to yoursite.com/api you will get a "Hello world" as response.
Now to add the header you want, this should do the trick:
get '/api' do
response['Access-Control-Allow-Origin'] = '*'
"Hello world"
end
Can't get 'Access-Control-Allow-Origin' header from fetch request
move your config from config/cors.rb
to config/initializers/cors.rb
all files in config/initializers/
will be loaded on rails startup.
also it could be possible to blocked by rails 6 new feature to block unwanted hosts.
add following snippet to config/application.rb
or env specific file in config/environments/
config.hosts.clear
check Upgraded Rails to 6, getting Blocked host Error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
Here is what you will have to do If you are making GET request, your client request have to send Origin header and then your server have to send the Access-Control-Allow-Origin header in the response. Values of both of these header have to be the same to allow cross origin resource sharing.
No 'Access-Control-Allow-Origin' header is present on the requested resource?
You don't need to (shouldn't be) generating the headers in every response.
In your case, I would wager the asset request from your browser is being "preflighted" with an OPTIONS request, but the CDN passes on the request without Access-Control request headers. The CDN thus (correctly) receives no CORS response headers from your Rails app, so the browser doesn't even attempt the GET request, and fails with the Cross-Origin error.
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
Your CDN needs be set up to forward the correct request headers to your app server such that it knows to generate the CORS headers. Then, the CDN will pass these CORS response headers along to the browser.
When you want OPTIONS responses to be cached, configure CloudFront to forward the following headers: Origin, Access-Control-Request-Headers, and Access-Control-Request-Method.
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-cors
If you make the change to your CDN for those headers and then invalidate your assets, your rack-cors
configuration by itself should work just fine.
# config/initializers/cors.rb
# @note: must be run after initializers/_assets.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
# All asset requests should be to rails prefixed assets paths
# serverd from the asset pipeline (e.g.: "/assets/*" by default)
resource "#{Rails.application.config.assets.prefix}/*",
# Allow any request headers to be sent in the asset request
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Headers
headers: :any,
# All asset fetches should be via GET
# Support OPTIONS for pre-flight requests
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
methods: [:get, :options]
end
end
Rails. No 'Access-Control-Allow-Origin' header is present on the requested resource
Looks like you're missing insert_before 0 according to the docs
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
Setting CORS headers do not solve my CORS problem
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.
CORS policy Access-Control-Allow-Origin header in the response mustn't be wildcard * when credentials include
In config.ru
adding credentials: true
and specifying the domain address in origins
fixed the issue
use Rack::Cors do
allow do
origins 'https://lets-meetup-app.herokuapp.com'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :patch, :options],
credentials: true
end
end
Related Topics
Rails Activerecord: Saving Nested Models Is Rolled Back
Rspec: How to Write Unit Test Case to Receive an Exception Which Is Getting Raised in Private Method
With Nokogiri I am Getting Error "Initialize': Getaddrinfo: No Such Host Is Known. (Socketerror)"
Multiple Limit Condition in Mongodb
Ruby Roo Loaderror: Cannot Load Such File -- Spreadsheet/Note
Linking to External File in Ruby on Rails
Writing a Ruby Extension in Go (Golang)
Passing Hashes Instead of Method Parameters
What's the Differences Between Ruby on Rails and Ruby
How to Replace a Pattern in Ruby Array
Sum of Arrays of Different Size
What Ruby and Rails Developers Ought to Know
Continuous Integration for Ruby on Rails
Writing a Pre-Push Hook in Git to Grep All Files for Regex Want to Reject Push If Regex Not Found
How to Sort a Ruby Array by Two Conditions
How to Verify Pacts Against an API That Requires an Auth Token