我正在研究AngularJS Node和MongoDB,我从互联网上获得了很棒的视频教程。在进入后面的章节时,我陷入了一个示例应用程序中,这似乎不起作用。
登录时出错
可能未处理的拒绝:{“消息”:“用户没有令牌”}
我的代码如下。
控制器 mainController.js
angular.module('mainCtrl',[])
.controller('MainController',function($rootScope, $location, Auth){
var vm = this;
vm.loggedIn = Auth.isLoggedIn();
$rootScope.$on('$routeChangeStart',function(){
vm.loggedIn = Auth.isLoggedIn();
Auth.getUser()
.then(function(data){
vm.user = data.data;
})
.catch(function (err) {});
});
vm.doLogin = function(){
vm.processig = true;
vm.err = '';
Auth.login(vm.loginData.username,vm.loginData.password)
.then(function(data){
vm.processig = false;
Auth.getUser()
.then(function(data){
vm.user = data.data;
});
if(data.success)
$location.path('/');
else
vm.error = data.message;
});
}
vm.doLogout = function(){
Auth.logout();
$location.path('/logout');
}
});
服务 authServices.js
angular.module('authService',[])
.factory('Auth',function($http, $q, AuthToken){
var authFactory = {};
authFactory.login= function(username,password){
return $http.post('/api/login',{
username:username,
password:password
})
.then(function(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/');
else
return $q.reject({message:"User have no token"});
}
return authFactory;
});
.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;
})
.factory('AuthInterceptor',function($q,$location,AuthToken){
var interceptorFactory = {};
interceptorFactory.request = function(config){
var token = AuthToken.getToken();
if(token){
config.headers['x-access-token'] = token;
}
return config;
};
interceptorFactory.responseError = function(response){
if(response.status == 403)
$location.path('/login');
return $q.reject(response);
}
return interceptorFactory;
});
我所缺少的.. ??
检查我的Projec Here