Simple Sinatra Ajax Not Working
Posted
by
proteantech
on Stack Overflow
See other posts from Stack Overflow
or by proteantech
Published on 2013-11-08T22:46:46Z
Indexed on
2013/11/09
3:55 UTC
Read the original article
Hit count: 154
I was trying make an AJAX call from a static file on my computer to a simple sinatra service. The ajax call was returning with an error and no details. The server logged no errors either. Another strange symptom was that the Origin in the request header was null.
I turns out that you can't make cross domain ajax calls without a little extra effort. You can set the Access-Control-Allow-Origin header on your sinatra response to expose your service to external domains using a snippet like this:
get '/hi' do
response['Access-Control-Allow-Origin'] = '*'
content_type 'text/plain'
"Hello World"
end
There's also another header you can set to allow other HTTP Methods besides gets, Access-Control-Request-Method. You can find more information by searching around for CORS: Cross Origin Resource Sharing and the previously mentioned headers.
Oh, and in case you want to do this in Rails as well you can do something like this in your controller:
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = '*'
end
© Stack Overflow or respective owner