I am working on an example rails api/angular app. I am using both devise
for rails, and angular-devise
on the front end. the problem right now is i am getting a No 'Access-Control-Allow-Origin' header is present on the requested resource
error when I try to authenticate.
at the suggestion of this answer i have added this to my application_controller
before_filter :add_cors_headers
def add_cors_headers
origin = request.headers["Origin"]
unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
origin = "http://api.marketplaceapi.dev"
end
headers['Access-Control-Allow-Origin'] = origin
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
allow_headers = request.headers["Access-Control-Request-Headers"]
if allow_headers.nil?
#shouldn't happen, but better be safe
allow_headers = 'Origin, Authorization, Accept, Content-Type'
end
headers['Access-Control-Allow-Headers'] = allow_headers
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '1728000'
end
and this to routes.rb
match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}
in my angular app, in my app.js, I have this defined;
.config(function ($routeProvider, AuthProvider, SERVER) {
$routeProvider
...
AuthProvider.registerPath(SERVER.url + '/users/sign_up.json');
AuthProvider.registerMethod('GET');
AuthProvider.resourceName('user');
});
and my AuthCtrl
angular.module('mpfeApp')
.controller('AuthCtrl', [
'$scope',
'$log',
'$location',
'Auth',
function register($scope, $location, $log, Auth) {
var credentials = {
email: 'email@mail.com',
password: 'password1',
passwordConfirmation: 'password1'
};
var config = {
headers: {
'X-HTTP-Method-Override': 'GET'
}
};
Auth.register(credentials, config).then(function(registeredUser) {
console.log(registeredUser);
}, function(error) {
console.log('error:' + error);
});
$scope.$on('devise:new-registration', function(event, user) {
console.log('from devise:new-registration event');
console.log(user);
});
}
]);
when I go to the register.html
page in my angular app, this is the console.log
output
OPTIONS: http://api.marketplaceapi.dev/users/sign_up.json
(index):1 XMLHttpRequest cannot load http://api.marketplaceapi.dev/users/sign_up.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 404.
does anyone have any tips for dealing with CORS in rails & angular? right now I am guessing the problem is coming from the de-coupled nature of this project. i was thinking about just putting them in the same repo, but that seems to defeat the whole premise of using rails as the api layer.
any help would be appreciated.