Search code examples
javascriptjquerybackbone.jsbackgrid

Backgrid/Backbone Pageable: Custom HTTP Headers with GET Request


I'm having trouble pushing a custom header in my requests when using the paging functions with Backgrid.js and Backbone-pageable.

The initial request is fetching the data correctly with custom headers being set using xhr.setRequestHeader.

How do I make all subsequent requests from backgrid send a custom header as well?

var MyCollection = Backbone.PageableCollection.extend({
        url: "http://api.myurl.com",
        // Initial pagination states
        state: {
            pageSize: 10,
            sortKey: "updated_at",
            order: 1
        },
        queryParams: {
            firstPage: 0,
            totalPages: null,
            totalRecords: null,
            sortKey: "sort",
            q: "state:active"
        },
        parseState: function (resp, queryParams, state, options) {
            return {totalRecords: resp.responseData.total_count};
        },
        parseRecords: function (resp, options) {
            return resp.responseData.items;
            console.log(options);
        }
    });
    var mycollection = new MyCollection();
    var grid = new Backgrid.Grid({
        columns: columns,
        collection: mycollection
    });
    // Render the grid and attach the root to your HTML document
    var $datagrid = $("#paginator-example-result");  
    $datagrid.append(grid.render().$el);

    var paginator = new Backgrid.Extension.Paginator({
        collection: mycollection
    });
    var myCustomRequestHeader = "ABCDEFG";
    // Render the paginator
    $datagrid.append(paginator.render().$el);
    mycollection.fetch({reset: true, beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader); }, type: 'POST'}); // This works as expected, the custom header is set in the first request

Thanks in advance!

Edit, based on John Moses' answer below, this is the working snippet:

var MyCollection = Backbone.PageableCollection.extend({
    ...
    sync: function(method, model, options){
        options.beforeSend = function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader);};
        return Backbone.sync(method, model, options);
    }
...
});

Solution

  • Override MyCollection's sync method:

    var MyCollection = Backbone.PageableCollection.extend({
    ...
    sync: function(method, model, options){
        options.beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader);
        return Backbone.sync(method, model, options);
    }
    ...
    });