Search code examples
ruby-on-railsangularjscodepen

Testing Rails API with AngularJS and Codepen


Having some trouble getting my pen to talk to my dev server on localhost.

I have an angularjs script which is using an $http.get request to get some json from the server, but it results in this error.

Access to XMLHttpRequest at 'localhost:3000/test' from origin 'https://s.codepen.io' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The Rails server and the browser are on the same machine, and I can call the page successfully if I just type the server url direclty into the browser, but I'm not sure how to address this error for scripts running in codepen.

In case of interest the request in my javascript is just:

$http.get("localhost:3000/test").then(
   function(response) {
     console.log("success");
   },
   function(response) {
      console.log("failed");
   }
 );

Solution

  • Try uncommenting the rack-cors gem in your Gemfile. Then in config/application.rb you can configure cors something like this:

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end
    

    Keep in mind, this will allow access from any origin. You'll probably want to change this for your production environment.