我是一名学生,最近正在研究angularJS拦截器,并尝试开发一个控制会话管理。我是平均堆栈开发的新手,需要帮助。 有没有人有一个angularJS会话管理的工作示例?
非常感谢您的帮助和时间。
答案 0 :(得分:3)
如果您想要基于令牌的控件,您可以执行以下操作:
你的拦截器:
angular.module('yourApp').factory('YourHttpInterceptor', ['$q', '$window',
function($q, $window) {
return {
'request': function(config) {
config.headers = config.headers || {};
// If you have a token in local storage for example:
if ($window.localStorage.token) {
// Add the token to "Authorization" header in every request
config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
// In your server you can check if the token is valid and if it's not,
// in responseError method you can take some action
}
// Handle something else
return config;
},
// Optional method
'requestError': function(rejection) {
// do something on request error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// Optional method
'response': function(response) {
// do something on response success
return response;
},
// optional method
'responseError': function(rejection) {
// Here you can do something in response error, like handle errors, present error messages etc.
if(rejection.status === 401) { // Unauthorized
// do something
}
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
}]);
在你的模块配置中注册拦截器:
angular.module('yourApp', []).config(function($httpProvider) {
$httpProvider.interceptors.push('YourHttpInterceptor');
}
正如您在this post中看到的,基于令牌的身份验证遵循以下步骤(几乎总是):