Put a custom http header in backbone

Juanma Jurado picture Juanma Jurado · Oct 25, 2012 · Viewed 8.8k times · Source

I am creating an API with Tastypie and I want to access to the API from Backbone. To send credentials I use an user_id and a api_key. I do this in android and with curl and this work great, but I can set the http header from backbone.

In curl I use:

 curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -H "user_id: 32" -H "api_key: 69950" -X DELETE "http://127.0.0.1:8000/api/v1/deletenote/66/?format=json" 

and in android java I use:

    HttpDelete requestDELETE = new HttpDelete();
    requestDELETE.setHeader("Content-type", "application/json");
    requestDELETE.setHeader("Accept", "application/json");
    requestDELETE.setHeader(Constants.HEADER_USER_ID, user_id);
    requestDELETE.addHeader(Constants.HEADER_API_KEY, key);

Both of them work great, but when I try this in Backbone following the responses that I found in other post from the page, this didn't work.

I am trying this:

var removeNote = new DeleteNoteModel({id:this.model.toJSON().id},{ query:this.model.toJSON().id});


removeNote.destroy({ 
        headers: {'user_id':dataWeb.get("id"),'api_key':dataWeb.get("api_key")}
        },{
                    async:false,
                    error: function(model, response){
                        console.log("KO_REMOVE_NOTE");
                        console.log(response);
                    },
                     success : function(model, response){
                        console.log("OK_REMOVE_NOTE");
                        console.log(response);
                     }
                }
    );

I'm putting the header when I call to the destroy call, but this don't send anithing to the server.

What I am doing in a wrong mode?

Thanks to all.

Answer

Tom Tu picture Tom Tu · Oct 25, 2012

Tallmaris answer should fix it for you though I would recommend usign jQuery ajaxSetup method to setup the headers as default values for all ajax requests as I believe you need them all the time anyway right?

Somewhere where you launch the App put in

$.ajaxSetup({
    headers: {
        'user_id':dataWeb.get("id"),
        'api_key':dataWeb.get("api_key")
    }
});

Thanks to that you'll save yourself a lot of repeated code :) keep it DRY!

(obviously you'd need to ensure that dataWeb is available in the scope of where you launch the app :) )