1

I want to put a headers in a post request to my REST service with Backbone.js , I try two ways :

this.model.save( { headers: {'X-Token' : myToken } } );

and with a setResquestHeader :

the function :

sendToken: function (xhr) {
        var tokenCookie;

        var name = "xtoken" + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) 
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) tokenCookie = c.substring(name.length,c.length);
        }
          xhr.setRequestHeader('X-Token', tokenCookie);
        }

the call :

this.model.save({ 
                beforeSend: this.sendToken,

                success: function() {

                    alert("success");
                },
                error: function(model,response,options) {
                    alert("error");

                }

            });     

But it doesn't seem to work , it doesn't send the header

user3214296
  • 73
  • 1
  • 11

1 Answers1

3

The signature for Model.save is model.save([attributes], [options]) . You have to pass an empty/null hash of attributes in order to add options :

this.model.save(null, {
    headers: {'X-Token' : 'myToken'}
});

And a demo http://jsfiddle.net/nikoshr/a4gss/

Or

this.model.save(null, {
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-Token', 'set token');
    }
});

http://jsfiddle.net/nikoshr/a4gss/1/

nikoshr
  • 32,926
  • 33
  • 91
  • 105