How do I set up Sinatra so that static files in the public folder are returned with the response Access-Control-Allow-Origin = \"*\" ?
This setup works for me:
Gemfile:
# Gemfile
gem 'sinatra'
gem 'sinatra-cross_origin'
Sinatra App:
# app.rb
require 'sinatra'
require 'sinatra/cross_origin'
class MyApp < Sinatra::Base
set :bind, '0.0.0.0'
configure do
#This is enable cross on the server
enable :cross_origin
end
#This before blocks gets invoked on every request and
#the (*) mark tells your server that share the resource with anyone,
#if you want to share it with specific domain you can mention the domain/s
#by removing the asterisk sign.
before do
response.headers['Access-Control-Allow-Origin'] = '*'
end
# routes...
options "*" do
response.headers["Allow"] = "GET, PUT, POST, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization,
Content-Type, Accept, X-User-Email, X-Auth-Token"
response.headers["Access-Control-Allow-Origin"] = "*"
200
end
end
The options block described above sends a 200 response to the preflight request sent by the browser. Then the browser makes the CORS request. In response to this request, the server sends Access-Control-Allow-Origin = * in response headers.
If we want only a specific domain to access the resources:
before do
response.headers['Access-Control-Allow-Origin'] = 'http://example.com'
end
this solution works for me and is based on an answer on a similar question How to add "Access-Control-Allow-Origin" headers to API Response in Ruby
get '/' do
response['Access-Control-Allow-Origin'] = '*'
"asdf" # return "asdf"
end
get '/foo' do
headers 'Access-Control-Allow-Origin' => 'http://example.com'
'hello world'
end
There's also a nice extension for cross origin sharing:
https://github.com/britg/sinatra-cross_origin
require 'sinatra'
require 'sinatra/cross_origin'
# To enable cross origin requests for all routes:
configure do
enable :cross_origin
end
# To only enable cross origin requests for certain routes:
get '/cross_origin' do
cross_origin
"This is available to cross-origin javascripts"
end
I did this on a server side, my file was called server.rb:
before do
content_type :json
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end
Have a look at this question here: Sinatra OPTIONS HTTP Verb. It's implemented in sinatra now so you don't have to hack around it.
If that doesn't help take a look at this blog post: Cross Origin Resource Sharing with Sinatra, and its repo at github: sinatra-corss_origin
Although the simplest way to do it should work just by adding this:
response['Access-Control-Allow-Origin'] = 'http://whatever.org'
before the return value in your route.