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? Tha
Object.save(
{'used': true}
{headers: {'Access-Token': 'access_token'}}
)
Backbone.$.ajaxSetup({
headers: {'Authorization' :'Basic USERNAME:PASSWORD'}
});
This code set headers to Backbone ajax, so they will be sent with every Backbone.sync. You will be able to send headers without using xhr.setRequestHeader
with every sync call.
So you don't need to do the following every time:
MyCollection.fetch({ headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );
You can just do
MyCollection.fetch();
Maybe it's kind of hack but it works perfectly for my system.
In the client side, add this before any server communication:
$.ajaxSetup({
xhrFields: {
withCredentials: true
},
async: true
});
In the server side add these headers (PHP):
header('Access-Control-Allow-Origin: http://your-client-app-domain');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Allow-Credentials: true');
Create a custom sync method that intercepts the calls to Backbone.sync and stuffs your authorization headers in and passes everything else through:
REPORTING_API_KEY = 'secretKeyHere';
CustomSync = function(method, model, options) {
options.headers = {
'Authorization' : 'Bearer ' + REPORTING_API_KEY
};
return Backbone.sync(method, model, options);
};
Then overwrite your model's sync with that one:
MyModel = Backbone.Model.extend({
urlRoot: '/api/',
sync: CustomSync
});