Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - Send token with every backbone sync request

My PHP api requires a user token be submitted with every request from my front-end Backbone app to make sure the user...

  1. Is active
  2. Has permissions to access the resource

What is the easiest way to set this up in Backbone? I am guessing the only way is to overwrite Backbone.sync, but what would the code look like? CoffeeScript preferred.

EDIT

Two more things
1. I would like to redirect the user to /login if I get a 403: Access Forbidden Error
2. I pull the user model which includes the token from localStorage when the app is bootstrapped
3. I have a baseModel and baseCollection which all models / collections come from

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...