简体   繁体   中英

AngularJS Http GET invalidates CSRF Token

I'm working on Symfony 3.2 and I'm trying to use some AJAX requests with AngularJS on some pages.

I have the following HTML code :

<div ng-app="timelineApp" ng-controller="timelineCtrl">
  <div id="timeline-container">
    <div ng-repeat="p in posts" class="w3-container w3-card-2 w3-white w3-round w3-margin"><br>
      // ...
    </div> 

    <div class="w3-card-2 w3-margin">
      <button ng-click="fetch()" id="fetch-button" class="w3-btn-block w3-btn w3-theme-d1 w3-round" type="button">Load 10 more posts.</button>
    </div>
  </div>
</div>

With the javascript:

  var app = angular.module('timelineApp', []).config(function($interpolateProvider){
      $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
  });

  app.controller('timelineCtrl', function($scope, $http) {
    $scope.offset = 0;
    $scope.posts = [];
    $scope.fetch = function() {
      var uri = "/api/timeline/{{ app.user.id }}/" + $scope.offset;
      $http
        .get(uri)
        .then(
          function(response) {
            $scope.posts = $scope.posts.concat(response.data.posts);
            $scope.offset += 1;

            if(response.data.posts.length < 10) {
              $('button#fetch-button').css('display', 'none');
            }
          }, 
          function(response) {
            console.log(response.status)
          } 
        )
      ;
    }

    $scope.fetch(); 
  });

And at some points in the page, I also have symfony forms that are simply put there with {{ form(form_name) }} .

If I don't let any AJAX request happen (ie, I remove the $scope.fetch(); and never click the button that also triggers the request), my forms work fine and I can submit any of them. But as soon as one ajax request is made, whatever form I post is rejected because of an invalid CSRF token.

I found some posts but none of them really helped, how can I prevent my AJAX requests from invalidating the forms ? Later on I'll have to also make POST requests with angular, I guess I'll have the same issue.

Ok so after some tries and debugging I actually figured out that, by writing var uri = "/api/timeline/{{ app.user.id }}/" + $scope.offset; the request was made to the production environment, while I'm currently testing in the dev environment with my browser. Hence the ambiguities on sessions.

A simple solution was to change this to var uri = "/{% if app.environment == 'dev' %}app_dev.php/{% endif %}api/timeline/{{ app.user.id }}/" + $scope.offset; so that, when testing in dev environment, the requests are also sent to dev environment. Everything is working alright now.

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