我正在尝试使用 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
在角度:
应用程序.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