3

I have created an HTTP response interceptor which checks for the 401 status code. If the code is 401, it is supposed to simply write in browser console, but this does not work. It doesn't even seem to catch it.

App.js:

   'use strict';

// Declare app level module which depends on views, and components
var app = angular.module('myApp', []);




app.factory('authHttpResponseInterceptor', ['$q', '$location', function ($q, $location) {
        return {
            response: function (response) {
                if (response.status === 401) {
                    console.log("Response 401");
                }
                else
                {
                    console.log("other response but no 401");
                }
                return response || $q.when(response);
            },
            responseError: function (rejection) {
                if (rejection.status === 401) {
                    console.log("Response Error 401", rejection);
                }
                return $q.reject(rejection);
            }
        }
    }])
        .config(['$httpProvider', function ($httpProvider) {
                //Http Intercpetor to check auth failures for xhr requests
                $httpProvider.interceptors.push('authHttpResponseInterceptor');
            }]);

Index.html

<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

  <div ng-controller="testCtrl"></div>

  <script src="bower_components/angular/angular.js"></script>
  <script src="app.js"></script>
  <script src="testController.js" type="text/javascript"></script>

</body>
</html>

testController.js

app.controller('testCtrl', function ($scope, $http, $timeout) {


    $http.get('http://ec2-54-229-72-240.eu-west-1.compute.amazonaws.com:8080/webservice/api/stuffs/onestuff', {
        headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')}
    }).success(function (data) {
        alert(data.id);
    });

});

The access token is stored in local storage from a previous landing/login page. What I'm trying to achieve is to redirect the user to this landing page if his token isnt valid anymore, or if he doesn't have one.

With a valid token, no problem, i successfully retrieve data from the api. But when I manually change the stored token, in order to trigger a 401, nothing is written in the browser console.

I'm sure that it's a 401 Unauthorized Reponse, because I checked it in Chrome network observer. Here's the only thing that i get :

XMLHttpRequest cannot load http://ec2-54-229-72-240.eu-west-1.compute.amazonaws.com:8080/webservice/api/students/chat. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. The response had HTTP status code 401.

And here are the requests ( yes, because sometime I have only one request in the list, and when I refresh the page it sometime append that there is two of them )

Name    Status     Type     Initiator
stuff    200       xhr       angular.js:10765
stuff    401       xhr       Other

Here's what i was talking about, for this time, when i refreshed the page i had two requests done, but it's strange because i only do one request in my code.

And sometime, after a few refresh i only have :

Name    Status     Type     Initiator
stuff    401       xhr       Other

But in both cases, I never had anything written in the console, which proves me that the 401 error has been caught.

Thank you, and sorry for bad english !

2 Answers 2

1

Try to add request and requestError functions (just in case, I know it is optional):

request: function(config) {
        return config;
      },
requestError: function(err) {
        $q.reject(err);
      },

http://jsfiddle.net/tjruzpmb/218/

I changed an url but it works. Please also notice my comments. Error 401 will never be catched in response() because interceptor always redirects 401 to responseError().

Sign up to request clarification or add additional context in comments.

Comments

0

Try replacing console.log with $log.log. You'll need to add it to the dependencies just like $q and $location.

as an example:

(function(){
  'use strict';
  angular.module('testModule', [])
         .factory('testFactory', testFactory);

  testFactory.$inject = ['$log', '$q', '$location'];
  function testFactory($log, $q, $location){
    $log.log('This will log to the console');
  }
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.