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.
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;
}
};
});
