Allowing Cross-Domain Access in Sinatra

I've been trying to make a little Sinatra app that accepts a "GET" request and sends back some JSON. But I kept getting a version of this error in my JavaScript console:

Origin http://domain.com is not allowed by Access-Control-Allow-Origin

Eventually I learned this was because I was making AJAX requests from one domain to another, which is generally not allowed for very good security reasons. That is, unless you explicitly allow it on the server side.

Naturally, Sinatra provides a ridiculously easy way to do this, which is explained extremely well by Functional Objects. Just add this line in the route somewhere before the result is sent to the requester:

response['Access-Control-Allow-Origin'] = 'http://domain.com'

To grant access to everyone, it's

response['Access-Control-Allow-Origin'] = '*'

I am so glad to see those errors disappear.