Sinatra CORS Example

1 min read ruby, sinatra, cors, api

Written in 2014. Tools, APIs and prices may have changed since.

Lab note What I wrote down while learning this by building with it. Short by design; the code is in pfeilbr/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);
});

Get new guides and courses by email

An occasional email when I publish a new guide, course or post. No spam, and you can unsubscribe any time.

Sent with Buttondown. I never share your address. Prefer a feed? Use the RSS feed.