2
votes

I have an angular app with a node/express backend. Ive attempted to implement an authentication interceptor using httpProvider. When there is a token stored in local storage the application works as expected and I am able to retrieve restricted data from the backend, but as soon as I delete the token by logging out and attempt to redirect to the main view, I get a TypeError: Cannot read property 'headers' of undefined. If I comment out the line of code in the config were Ive registered the interceptor the error is gone. For some reason that I have not been able to diagnose, the application crashes unless there is a token in local storage.

enter image description here

Authentication Interceptor:

angular.module('barmehealth')
  .factory('authInterceptor', function(authToken) {

    return {
      request: function(config) {
        var token = authToken.getToken();

        if (token)  {
          config.headers.Authorization = 'Bearer ' + token;

          return config;
        }
      },
      response: function(response) {
       return response;
      }
    };
  });

Registered in the Config object:

$httpProvider.interceptors.push('authInterceptor');

I attempted to fix the problem by changing the code as follows:

.factory('authInterceptor', function(authToken) {

  return {
    request: function(config) {
      var currentToken = authToken.getToken();
      var token = currentToken ? currentToken : null;

      if (token)  {
        config.headers.Authorization = 'Bearer ' + token;

        return config;
      }
    },
    response: function(response) {
      return response;
    }
  };
});
1

1 Answers

1
votes

Your auth interceptor only conditionally returns config. This is a logical error. Fix it like this:

request: function(config) {
  var token = authToken.getToken();

  if (token)  {
     config.headers.Authorization = 'Bearer ' + token;
  }

  return config;
}

It's important not to put your only return statement inside of an if block. Otherwise, if there is no token, no config will be returned and things will get hairy.

The error is being thrown because when there is no token and config is not returned, the angular serverRequest method tries to access config.headers and finds that config is undefined because you didn't return it.