Update:
I was writing a small module to handle this csrf token problem in backbone until I got push notification of @Louis's answer.
His answer is quite elegant and seems nice, but I'll leave a link to my backbone.csrf module github repo just for anyone who needs it.
====================================================================
I'm using Backbone as my frontend framework along with my Django backend.
I had to configure my Backbone.sync
to set CSRF request header for every single AJAX requests before it sends it, for compatibility with Django's CSRF protection system.
Since I was using require.js for modular javascript development, I tried to configure this in shim.init
of require.config
so that this overriding will be fired as soon as the Backbone is loaded on browser:
<script>
var require = {
...
shim: {
'jquery': {'exports': 'jQuery'},
'backbone': {
'deps': ['underscore', 'jquery'],
'exports': 'Backbone',
'init': function(_, $) {
alert('NOT EVEN CALLED');
var originalSync = this.Backbone.sync;
this.Backbone.sync = function(method, model, options) {
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-CSRFToken', window.csrf_token);
}
return originalSync(method, model, options);
}
}
}
}
}
</script>
// Load require.js
<script src="require.js"></script>
Although the Backbone has been successfully loaded, the 'init' of the require configuration doesn't get called.
What is the problem?