AngularJS&快递:$ rootScope。$未正确刷新

时间:2016-10-10 23:33:42

标签: angularjs express

用户登录后,会创建一个json Web令牌,然后保存在本地存储中。但是,我的快速中间件正在返回消息:'没有提供令牌'。一旦我在浏览器中点击刷新,它就会正确检测到令牌并且用户显示为已登录。我想这是一个简单的修复,但我无法弄明白。有什么想法吗?

角度控制器:

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

角度身份验证服务:

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

将角色附加到所有请求的角色配置文件:

angular.module('userApp', ['appRoutes', 'userControllers', 'mainController', 'authService'])

.config(function($httpProvider) {
    $httpProvider.interceptors.push('AuthInterceptor');
});

快递:

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

0 个答案:

没有答案