Sinatra CORS Example
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);
});