JetThoughts Archives Blog

Allow multiple access control requests for Rails

December 22nd 2010

If you have problem with sending XHR requests from different domains, you find trouble to get content, because

XMLHttpRequest cannot load http://different.domain.local:3000/visits. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.

The solution is to setup response headers: Access-Control-Request-Method, Access-Control-Allow-Origin.

1headers['Access-Control-Allow-Origin'] = '*'
2headers['Access-Control-Request-Method'] = '*'

Example for rails:

1#app/application_controller.rb
2after_filter :set_access_control_headers
3
4def set_access_control_headers
5  headers['Access-Control-Allow-Origin'] = '*'
6  headers['Access-Control-Request-Method'] = '*'
7end

You can look to sources of the sample Sinatra application in GitHub. Demo live in Heroku. Or use these smaples.

If you have questions or some help, feel free to contact me: michael@jetthoughts.com

Author: Michael Nikitochkin

blog comments powered by Disqus