Backbone uses jQuery's $.ajax, so you can use $.ajaxSetup to "set default values for future Ajax requests":
$.ajaxSetup({
headers: {
"accept": "application/json",
"token": YOUR_TOKEN
}
});
Update: an improvement to this idea (thanks to @Glen) is to use $.ajaxSend to check for the existence of a token each time before setting it in the headers of the request:
$(document).ajaxSend(function(event, request) {
var token = App.getAuthToken();
if (token) {
request.setRequestHeader("token", token);
}
});
Where App.getAuthToken() is a function in your Backbone app.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…