2

I'm working on a backbonejs app which utilises a RESTful API for all the model data. I need to be able to pass a customer HTTP header for authentication, which includes a localStorage item, to all ajax calls made through the model's fetch(), save(), etc.

I know how to pass the header for each one individuall, but I can't figure out a way to do it for all calls without copying/pasting the same code over and over. I've read some things about overriding the backbonejs sync, but I can't quite understand how I could do that.

I've decided to create a 'BaseModel' which all my other models would extend from, thinking this might be an easy way to do this (it's made it easy for my api url root).

Here is the basics of my models:

BaseModel:

var Backbone = require("backbone");

// Declare our options we'll use to extend the base view
var modelOptions = {
apiUrl: 'api.php/v1.1',
};

// Export our extended view
module.exports = Backbone.Model.extend(modelOptions);

Sample Model:

var BaseModel = require("./baseModel");

// Declare our options we'll use to extend the base view
var modelOptions = {
    initialize: function() {
        this.url = this.apiUrl+'/Cars';
    },
};
// Export our extended view
module.exports = BaseModel.extend(modelOptions);
halfer
  • 19,824
  • 17
  • 99
  • 186
David
  • 16,246
  • 34
  • 103
  • 162
  • Hey David, don't use `$.ajaxSetup`. You're on the right track with the base model and it's what I've done in the past. See my [`AuthModel` and `AuthCollection` example](https://stackoverflow.com/a/41991573/1218980). – Emile Bergeron Dec 25 '18 at 05:07

2 Answers2

1
$.ajaxSetup({
    headers: { 'custom-header': ' value' }
});

Also, you can add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('custom-header', 'value');
    }
});
shahista inamdar
  • 176
  • 2
  • 12
0

I believe you can set the global AJAX header through jQuery like:

$.ajaxSetup({
    headers: yourCustomHeader
}); 

or

Backbone.$.ajaxSetup({
    headers: yourCustomHeader
});
Eliellel
  • 1,426
  • 1
  • 9
  • 14