How to clean 401 in an application based on Backbone.js

In my Backbone.js based application, I am talking to my API, which answers 401 if the basic request was made without or with an invalid authentication token. I would like to do this by going to the #login page every time 401 is accepted.

To get 401, I successfully wrapped Backbone.sync, but at that moment I was stuck. I tried several strategies here:

  • throw 'unauthorized' down in Backbone :: sync and try to find in my router. Error: "Unused Unauthorized"

  • Trying #.navigate '#login' down in Backbone :: sync, which not only looks weird, but also related to the problem that my application is based on AMD / require.js and I cannot just access my Backbone instance. Router in my wrapped sync function.

The only solution that I see so far would be to create a “globally accessible” caching object that receives a link to my router instance and, in turn, is placed in define as a dependency where necessary. This cache object was supposed to be a single and broke my whole strategy of "please - non-global and without names."

I'm kinda stuck here. Can someone point me to a cleaner solution to this common problem?

+8
javascript requirejs amd
source share
2 answers

You can do the redirection in ajaxError:

 $.ajaxError(function (event, xhr) { if (xhr.status == 401) window.location = '#login'; }); 

If everything is configured correctly, you do not need to access the router instance manually. Going to this URL should initiate a route function associated with it.

+8
source share

For those using jQuery 1.8 or higher, the syntax has changed:

 $(document).ajaxError(function (event, xhr) { if (xhr.status == 401) window.location = '#login'; }); 

See the jQuery tutorial for more details.

+3
source share

All Articles