Работя върху примерно приложение за rails api/angular. Използвам както devise
за релси, така и angular-devise
в предния край. проблемът в момента е, че получавам грешка No 'Access-Control-Allow-Origin' header is present on the requested resource
, когато се опитвам да удостоверя.
по предложение на този отговор добавих това към моя 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
и това към routes.rb
match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}
в моето ъглово приложение, в моя app.js, имам това дефинирано;
.config(function ($routeProvider, AuthProvider, SERVER) {
$routeProvider
...
AuthProvider.registerPath(SERVER.url + '/users/sign_up.json');
AuthProvider.registerMethod('GET');
AuthProvider.resourceName('user');
});
и моя AuthCtrl
angular.module('mpfeApp')
.controller('AuthCtrl', [
'$scope',
'$log',
'$location',
'Auth',
function register($scope, $location, $log, Auth) {
var credentials = {
email: '[email protected]',
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);
});
}
]);
когато отида на страницата register.html
в моето приложение angular, това е изходът console.log
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.
някой има ли някакви съвети за справяне с CORS в релси и ъглови? точно сега предполагам, че проблемът идва от необвързания характер на този проект. Мислех просто да ги поставя в едно и също хранилище, но това изглежда опровергава цялата предпоставка за използване на релси като api слой.
всяка помощ ще бъде оценена.