Sinatra CORS Example

1 min read ruby, sinatra, cors, api

Sinatra CORS Example

An example Sinatra json rest api app showing CORS support by setting the appropriate HTTP headers

Core Code

Set appropriate headers in before filter block

before do
   content_type :json    
   headers 'Access-Control-Allow-Origin' => '*', 
            'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST', 'PUT'],
            'Access-Control-Allow-Headers' => 'Content-Type'   
end

Running

bundle install
foreman start

Testing

Run the following from a another non-localhost domain

$.get('http://localhost:<port>/movie', function(data) {
	console.log(data);
});
$.post('http://localhost:<port>/movie', {movie: 'The Godfather'}, function(data) {
	console.log(data);
});