Got CSRF verification failure when while requesting POST through API

前端 未结 2 797
一向
一向 2021-01-28 12:48

I\'m writing a site using REST API. I use django with piston at backend (also using corsheaders.middleware.CorsMiddleware with CORS_ORIGIN_ALLOW_ALL = True). And I use backbone.

2条回答
  •  悲哀的现实
    2021-01-28 13:10

    Sounds like you need to pass the CSRF token through with your save request.

    One solution would be to pass the CSRF token back to the model requesting it, then override your model's save method ensuring the model passes the CSRF token back with it.

        Question = Backbone.Model.extend({
            urlRoot: 'http://example.com/api/questions',
    
            defaults: {
                csrf: null,
                id: null,
                title: '',
                text: ''
            },
    
            initialize: function() {
                //alert(this.title);
            }
    
            save: function( data, options ){
    
                 data = $.extend( true, {
                   csrf: this.get( 'csrf' )
                 }, data );   
    
                 options = _.extend( options, {
                     error: onError,
                     success: onSuccess
                  } );
    
                 // Call super method.
                 Backbone.Model.prototype.save.apply( this, [ data, options ] );
            }
    
        });
    

提交回复
热议问题