我正在尝试使用Angular中的资源服务向Rails API发送POST请求。角度客户端和API都不在同一服务器中(因此存在跨域)。
我无法发送请求,我想我可能有多个问题(我认为角度控制器或服务是错误的)并且我可能遇到CSRF(跨域)问题。
我已经阅读了很多帖子,并添加了一些建议,所以现在,我混合了所有这些,这是行不通的。
出于CSRF目的:
在rails中我添加了:
应用程序控制器:
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :set_csrf_cookie_for_ng
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
protected
def verified_request?
super || form_authenticity_token == request.headers['X_XSRF_TOKEN']
end
end
角度:
app.js:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'myApp.i18n']).
config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.when('/boat-booking', {templateUrl: 'partials/boat-booking.html', controller: 'BoatBookingCtrl'});
$routeProvider.otherwise({redirectTo: '/home'});
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
}]);
用于发送POST请求目的:
我有一个控制器,我想发送一个变量:
.controller('BusinessCtrl', function ($scope, $location, Business) {
$scope.createBusiness = function() {
//var business = {name: "business1"};
alert ("business:" + $scope.business);
alert ("businessName:" + $scope.business.name); // This is showing the business name, so the value is in scope.
$scope.business = Business.save($scope.business);
};
});
服务:
.factory('Business',
function($resource){
var businesses =
$resource('http://127.0.0.1\\:3000/:business', {}, {
query: {method:'GET', params:{business:'businesses'}, isArray: true},
save: {method:'POST', params:{business:'businesses'}, isArray: false}
});
return businesses;
}
);
当我执行此操作时,我得到:
Started OPTIONS "/businesses" for 127.0.0.1 at 2013-11-04 10:41:20 +0100
ActionController::RoutingError (No route matches [OPTIONS] "/businesses"):
在rails日志中。我尝试过使用不同错误消息的其他组合,但没有一个能够正常工作。
谢谢, 罗伯特。
更新
如果我从控制器中的角度服务调用中删除参数,例如:
$scope.business = Business.save();
然后,Rails中的日志会发生变化。现在,我发送POST请求而不是OPTIONS。但是,我还有其他一些错误......
Started POST "/businesses" for 127.0.0.1 at 2013-11-04 11:00:31 +0100
Processing by BusinessesController#create as HTML
Can't verify CSRF token authenticity
Businesses_controller.create!!!!!
Completed 400 Bad Request in 1ms
答案 0 :(得分:1)