On web application, the standard will have javascript code. Especially with ajax call method and event driven application design.
One of my experience just now was with using promise in javascript. It not catch the error status code returned from the server backend, but in debug mode in the browser status returned was 401 or unauthorized. I using Marionette JS as my development framework and my backend using Chicagoboss.
So the story was that user need to login before access the API. When request coming without authorization code, it will return 401 status code. My backend API try to be Restfull. And i want my web application automatically cacth the 401 error globally and will show login form when 401 status code encountered within the app run time. So the code was like below :
var defer = $.Deferred(); options || (options = {}); options.reset = true; defer.then(options.success, options.error); var response = data.fetch(_.omit(options, 'success', 'error')); response.done(function(){ defer.resolveWith(response, [edonationboxes]); }); response.fail(function(response){ defer.reject(response); });
And i have the ajax setup when the webapp start to detect the 401 globally.
$.ajaxSetup({ statusCode: { 401: function(){ // Redirec the to the login page. window.location.replace('#login'); }, 403: function() { // 403 -- Access denied window.location.replace('/#denied'); } }, });
So the problem is when i refresh page, it correctly detect the 401 and login page shown. But when application run and the request triggered within the app, by accessing a menu, it not cacthing the 401 error.
When debugging, the statusCode was 0. So google for a while, seems issue with the API backend which not returning correct headers for CORS request. So when fixed the app behave correctly. Login page show when 401 detected.
So make sure in the API response header return this : access-control-allow-origin:*
With javascript promise, it wont behave correctly if CORS involved and not set correctly, especially in SPA web application.
Hope this helps someone, as i have debug this almost 3 hours.
0 comments:
Post a Comment