Backbone.js上的Laravel 5 TokenMismatch使用_token设置destroy方法

时间:2015-07-30 23:00:10

标签: backbone.js laravel-5.1

我试图通过以下方式删除模型:

var FeaturedUsersView = Backbone.View.extend({
    events: {
        "click .remove-featured-user" : "removeFeaturedUser"
    },
    template : _.template(FeaturedUsersTemplate),
    render: function(){
        this.$el.html(this.template({ featuredUsers:  App.featuredUsers.toJSON() })); 
        return this;
    },
    removeFeaturedUser: function(event) {
        userToRemove = this.collection.get(event.target.id);
        userToRemove.set("_token", $('input[name="_token"]').val());
        userToRemove.destroy({
            wait: true,
            /*
             *headers: {
             *    _token : $('input[name="_token"]').val()
             *},  
             *async: false,
             */
            url: '/api/admin/versions/' + App.config.get("class_id") + '/featured_users',
        });


    }
});

我一直收到错误:异常' Illuminate \ Session \ TokenMismatchException'。

这个视图有一个使用相同标记的model.save()。我有一种感觉,destroy方法忽略了DELETE请求中的令牌。有什么提示吗?

这是backbone.js的破坏方法:

destroy: function(options) {
  options = options ? _.clone(options) : {};
  var model = this;
  var success = options.success;
  var wait = options.wait;

  var destroy = function() {
    model.stopListening();
    model.trigger('destroy', model, model.collection, options);
  };

  options.success = function(resp) {
    if (wait) destroy();
    if (success) success.call(options.context, model, resp, options);
    if (!model.isNew()) model.trigger('sync', model, resp, options);
  };

  var xhr = false;
  if (this.isNew()) {
    _.defer(options.success);
  } else {
    wrapError(this, options);
    xhr = this.sync('delete', this, options);
  }
  if (!wait) destroy();
  return xhr;
},

1 个答案:

答案 0 :(得分:0)

添加此全局修复了我的问题:

<meta name="csrf-token" content="{{ csrf_token() }}">


$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});