Reputation: 11639
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?
Upvotes: 0
Views: 811
Reputation: 7655
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
Upvotes: 0