Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add request header on backbone

My server has a manual authorization. I need to put the username/password of my server to my backbone request inorder for it to go through. How may i do this? Any ideas? Thank you

like image 496
n0minal Avatar asked Apr 10 '12 00:04

n0minal


2 Answers

Models in Backbone retrieve, update, and destroy data using the methods fetch, save, and destroy. These methods delegate the actual request portion to Backbone.sync. Under the hood, all Backbone.sync is doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.

fetch, save, and destroy all accept an additional parameter [options]. These [options] are simply a dictionary of jQuery request options that get included into jQuery ajax call that is made. This means you can easily define a simple method which appends the authentication:

sendAuthentication = function (xhr) {   var user = "myusername";// your actual username   var pass = "mypassword";// your actual password   var token = user.concat(":", pass);   xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token)))); } 

And include it in each fetch, save, and destroy call you make. Like so:

 fetch({   beforeSend: sendAuthentication   }); 

This can create quite a bit of repetition. Another option could be to override the Backbone.sync method, copy the original code and just include the beforeSend option into each jQuery ajax request that is made.

Hope this helps!

like image 152
shanewwarren Avatar answered Oct 20 '22 06:10

shanewwarren


The easiest way to add request header in Backbone.js is to just pass them over to the fetch method as parameters, e.g.

MyCollection.fetch( { headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } ); 
like image 28
tmaximini Avatar answered Oct 20 '22 06:10

tmaximini