I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is:
Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () {
return $window.localStorage.getItem('token');
}' is not a valid HTTP header field value.
Any assistance with this problem would be greatly appreciated.
File: authService.js
angular.module('authService', [])
// ===================================================
// auth factory for login and user information handling
// dependencies: $http for API communication, $q for promise objects, AuthToken for token management
// ===================================================
.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};
authFactory.login = function(username, password) {
return $http.post('/api/authenticate', {
username: username,
password: password
})
.success(function(data) {
console.log(data);
AuthToken.setToken(data.token);
return data;
});
};
authFactory.logout = function() {
AuthToken.setToken();
};
authFactory.isLoggedIn = function() {
if (AuthToken.getToken())
return true;
else
return false;
};
authFactory.getUser = function() {
if (AuthToken.getToken())
return $http.get('/api/me', { cache : true});
else
return $q.reject({ message : 'User has no token.'});
};
return authFactory;
})
// ===================================================
// factory for managing tokens
// dependencies: $window for client-side token storage
//
//
// ===================================================
.factory('AuthToken', function($window) {
var authTokenFactory = {};
authTokenFactory.getToken = function() {
return $window.localStorage.getItem('token');
};
authTokenFactory.setToken = function(token) {
if (token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
};
return authTokenFactory;
})
...
File: app.js
var app = angular.module('userApp', [
'ngAnimate', 'app.routes', 'authService', 'mainCtrl', 'userCtrl', 'userService']);
app.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
app.controller('mainController', function($http) {
var vm = this;
vm.message = 'Hey! Message';
$http.get('/api/users')
.then(function(data) {
vm.users = data.users;
});
});