0
votes

Here is my Rails app's application controller:

class ApplicationController < ActionController::API
  before_filter :add_allow_credentials_headers

  def add_allow_credentials_headers
    response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
  end
end

This is my Angular app's controller using the $http service and a custom factory:

'use strict';
angular.module('usausa', []).controller('obtainPovertyData',
  ['$scope', '$http', 'getPovertyData', function($scope, $http, getPovertyData) {
  getPovertyData.getPoverty().success(function(data){
    console.log("hi")
    console.log(data)
  }).error(function(error){
    console.log("hi1")
    console.log(error)
  })
}]);

This is my getPovertyData factory:

'use strict';
var usausa = angular.module('usausa');
usausa.factory('getPovertyData', ['$http', function($http){
  return {
    getPoverty: function() {
      return $http.get('localhost:3000/api/v1/poverty/data')
    }
  }
}])

Right now my rails endpoint is just on localhost:3000. My angular app is running on localhost:5555. I'm using Chrome. For some reason when I run my angular app and visit my index.html, I see this in my console:

XMLHttpRequest cannot load localhost:3000/api/v1/poverty/data. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Why is this happening? I thought I solved this issue no when I allowed the request to come from any origin?

1
this has nothing to do with angularcharlietfl
What does it have to do with?Jwan622
CORS is a server configuration issue that has nothing to do with the clientcharlietfl
It's weird to me that CORS (seemingly to protect the server from any client making sensitive AJAX requests that may alter resources) is something on the client side. With that said, it looks like my rails API is allowing requests from any origin. So, why am I still having this problem?Jwan622
because there is more involved than 2 headers. Is server configured to process OPTIONS requests and all the CORS headers required for those?charlietfl

1 Answers

0
votes

There is a gem rack-cors which you can use to configure cross origin requests in your Rails app.

For example, to allow request under /api route, use the following config:

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