简体   繁体   中英

Angular JS & CSRF with RESTFull API Laravel

Can't understand how to make it work... I am trying to get the CSRF from the API and load it as a constant in my angularJS app. Here is the code I used from @David Mosher https://gist.github.com/davemo/6141699 I start the app.js by doing that:

    // Retrieve and inject the CSRF token from the server
(function() {
  var $injector = angular.injector(['ng']); $injector.invoke(function($http,$rootScope) {
    $rootScope.$apply(function() {
      $http.get("http://api.local/auth/csrf_token").then(function(response)
      {
        angular.module("app").constant("CSRF_TOKEN", response.data);
        console.log(CSRF_TOKEN);
        angular.bootstrap(document, ['app']);
      });
    });
  });
})();

When I check it returns a 200 with the csrf_token. However the CSRF_TOKEN is set nowhere in the app... the console.log(CSRF_TOKEN) return ReferenceError: CSRF_TOKEN is not defined....

Any idea what I am doing wrong??

Thank you so much! :-)

I use angular in my laravel project too. Here is what I do, and it works for me:

for starting angular I use this (I need this [[ for no conflict with blade {{ syntax.):

var laravelApp = angular.module('laravelApp', ['ui.bootstrap', 'ngResource'], function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

In my index.blade.php I define the csrf token as a constant:

@section('javascripts')
    <script>
        angular.module("laravelApp").constant("CSRF_TOKEN", '{{ csrf_token() }}');
    </script>
@endsection

And in my Controller I use this CSRF_TOKEN constant in angular as well:

laravelApp.controller('startCtrl', function($scope, $http, CSRF_TOKEN, $window) {

    // init
    $scope.init = function () {
        $scope.template_choose = 'start';
        $scope.loadTemplateURL = '/template/load';
    }

    // POST Request with csrf_token
    $scope.loadActualTemplate = function() {
        $http.post($scope.loadTemplateURL, {
            '_token' : CSRF_TOKEN
        }).then(function(Response) {
            $scope.template_choose = '/template/choose/'+Response.data;
        });
    }

    // start
    $scope.init();
});

Define your CSRF_TOKEN in your blade template. Deliver it in your controller. Use it as a Post Parameter in your $http.post. And this works :)

如果您有一个,将上面显示的代码移到services.js顶部

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM