Tuesday, July 10, 2012

Adding HTTP headers to AJAX calls in Backbone.js

Just a quick note about setting custom header in the HTTP request that Backbone.js manages. This is super easy to do. In the example code below, I have a Backbone.Collection assigned to messagesCollection variable and I'm triggering a fetch on that collection: messagesCollection.fetch({ headers: { 'x-my-custom-header-1':'foobar', 'x-my-rest-api-version':'1.0' } });

5 comments:

  1. Thanks for this, I couldn't find anything about headers in the Backbone docs.

    Also, if anyone wants to add default headers (such as a REST token) to all their backbone sync calls, you can do this:

    (function(){
    // Store the native, default sync method, we'll wrap this.
    Backbone._nativeSync = Backbone.sync;

    // Create our default options object
    Backbone.defaultSyncOptions = {};

    // Ever so gingerly wrap the native sync
    // in a method that combines options
    Backbone.sync = function( method, model, options) {
    Backbone._nativeSync( method, model,
    _.extend( {}, Backbone.defaultSyncOptions, options ) );
    };
    })();

    // then just set the options:
    Backbone.defaultSyncOptions = { headers: { "foo":"bar" } };

    ReplyDelete
  2. Tyler, thanks for posting that.

    ReplyDelete