Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to catch 401 status code with Angular HttpInterceptor

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 !

like image 833
Nuzzob Avatar asked Jun 24 '26 06:06

Nuzzob


1 Answers

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().

like image 93
Krystian Pudlik Avatar answered Jun 25 '26 19:06

Krystian Pudlik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!