How to load XMLHttpRequest?

How do I load a JSON file into my Rails app from Amazon S3 if I have the error that "XMLHttpRequest cannot load X. Origin X is not allowed by Access-Control-Allow-Origin."?

  • I am trying to load a JSON file hosted on Amazon S3  into a MustacheJS template in my rails app. But the data is not passing through. The error in the console is XMLHttpRequest cannot load http://dfndrr.s3.amazonaws.com/test/posts.json. Origin http://dfndrr-dev.herokuapp.com is not allowed by Access-Control-Allow-Origin. Here is the file. I am just using this for testing and learning and this is obviously not how I would structure apps long term https://github.com/JGallardo/tutorials/blob/master/ruby/dfndrr-dev/app/views/blog/index.html.erb I have been browsing Google and though I find some answers, I am not sure how to put it all together. For example, this person solved this but in a Sinatra app. I just need to know how to do this in rails. https://gist.github.com/miry/5447203

  • Answer:

    The best and easiest way is looking into CORS. Amazon S3 has a guide for setting it up: http://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html. You do lose support for older browsers like IE7, though. If you want a brittle, hack-y, and generally messy solution, you can mimic JSONP. See this: https://forums.aws.amazon.com/message.jspa?messageID=190557 Another (even less preferred) technique would be aliasing S3 under a subdomain (i.e. static.example.com) and using iframes.

Brian Chu at Quora Visit the source

Was this solution helpful to you?

Other answers

Your problem here is that you are asking the client (i.e. browser) to access a 3rd party web site. Browser security will not let you do that. You need to pass the request to your own server and that server is then able to get the JSON from this 3rd party web site, and then the server passes that JSON back to the browser.

Brian Staff

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.