title: AngularJS & Express: $rootScope.$on not refreshing properly
body: <p>Once users login, a json web token is created and then saved in local storage. However, my express middleware is returning <strong>message: 'No token provided'</strong>. Once i hit refresh in the browser, then it detects the token properly and the user is shown as logged in. I imagine this is a simple fix but I have not been able to figure it out. Any ideas please?</p>
  
  <p><strong>Angular Controller:</strong></p>
  
  <pre><code>angular.module('mainController', ['authService'])
  
  .controller('mainCtrl', function($http, $timeout, $location, Auth, $rootScope, $route) {
  
      var app = this;
  
      $rootScope.$on('$routeChangeStart', function() {
          app.loggedIn = Auth.isLoggedIn();
  
          Auth.getUser().then(function(data) {
              app.user = data.data;
              console.log(app.user);
          });
      });         
  
      app.doLogin = function(userData) {
          app.user = false;
          app.loading = true;
          app.errorMsg = false;
          Auth.doLogin(app.userData).then(function(data) {
              if (data.data.success) {
                  app.loading = false;
                  app.successMsg = data.data.message + '...Redirecting';                                  
                  $timeout(function() {
                      $location.path('/');
                  }, 2000);
              } else {
                  app.loading = false;
                  app.errorMsg = data.data.message;
              }
          });
      };
  </code></pre>
  
  <p><strong>Angular Authentication Service:</strong></p>
  
  <pre><code>angular.module('authService', [])
  
  .factory('Auth', function($http, AuthToken, $q) {
      var authFactory = {};
  
      authFactory.doLogin = function(userData) {
          return $http.post('/api/authenticate', userData).then(function(data) {
              AuthToken.setToken(data.data.token);
              return data;
          });
      };
  
      authFactory.doLogout = 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');
          } else {
              return $q.reject({ message: 'User has no token' });
          }
      }
  
      return authFactory;
  })
  
  .factory('AuthToken', function($window) {
      var authTokenFactory = {};
  
      authTokenFactory.setToken = function(token) {
          if (token) {
              $window.localStorage.setItem('token', token);
          } else {
              $window.localStorage.removeItem('token');
          }
  
      };
  
      authTokenFactory.getToken = function() {
          return $window.localStorage.getItem('token');
      };
  
      return authTokenFactory;
  })
  
  .factory('AuthInterceptor', function($location, $q, AuthToken) {
      var AuthInterceptorFactory = {};
  
      var token = AuthToken.getToken();
  
      AuthInterceptorFactory.request = function(config) {
          if (token) config.headers['x-access-token'] = token;
          return config;
      };
  
      AuthInterceptorFactory.responseError = function(response) {
          if (response.status === 403) {
              AuthToken.setToken();
              $location.path('/login');
          }
          return $q.reject(response);
      };
  
      return AuthInterceptorFactory;
  });
  </code></pre>
  
  <p><strong>Angular Config File to Attach Tokens to all requests:</strong></p>
  
  <pre><code>angular.module('userApp', ['appRoutes', 'userControllers', 'mainController', 'authService'])
  
  .config(function($httpProvider) {
      $httpProvider.interceptors.push('AuthInterceptor');
  });
  </code></pre>
  
  <p><strong>Express:</strong></p>
  
  <pre><code>// middleware to check for tokens
  router.use(function(req, res, next) {
      var token = req.body.token || req.body.query || req.headers['x-access-token'];
  
      if (token) {
          jwt.verify(token, secret, function(err, decoded) {
              if (err) {
                  res.json({ success: false, message: 'failed to authenticate token' });
              } else {
                  req.decoded = decoded;
                  next();
              }
          });
      } else {
          res.json({ success: false, message: 'No token provided'});
      }
  });
  
  // Route to get the current user
  router.get('/me', function(req, res) {
      res.send(req.decoded);
  });
  </code></pre>