如果 angularjs 中的状态代码为 403,请注销
Log out if status code is 403 in angularjs
我有一个SPA(单页应用程序),它向服务器发送大量http请求,服务器检查发送请求的用户是否经过身份验证。
如果用户未通过身份验证,我会将他重定向到如下所示的登录页面:
$scope.getGroups = function () {
$http({
method: "get",
url: "/enterprises/groups"
}).success(function (response) {
GroupService.updateGroups(response.groups);
}).error(function (errResponse, status) {
if(status == 403){
$location.path("login")
}
});
};
问题是我有很多http请求,我不想每次都处理"禁止"异常。
有没有办法编写这种代码,比如说,配置并在任何地方应用它?
您可以创建一个服务来处理此问题,并将其添加到$http
拦截器中。作为如下服务:
app.factory('authInterceptorService', ['$q','$location', function ($q, $location){
var responseError = function (rejection) {
if (rejection.status === 403) {
$location.path('login');
}
return $q.reject(rejection);
};
return {
responseError: responseError
};
}]);
然后将其添加到 in config
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
}]);
然后,这将适用于提出的所有请求。
我最近在自己的应用程序中遇到了需要相同的操作,最终在$httpProvider上使用了拦截器。这种事情:
angular.module('notesApp', [])
.controller('MainCtrl', ['$http', function($http) {
...
}]).factory('MyLoggingInterceptor', ['$q', function($q) {
return {
request: function(config) {
console.log('Request made with ', config);
return config;
// If an error, or not allowed, or my custom condition
// return $q.reject('Not allowed');
},
requestError: function(rejection) {
console.log('Request error due to ', rejection);
// Continue to ensure that the next promise chain
// sees an error
return $q.reject(rejection);
// Or handled successfully?
// return someValue;
},
response: function(response) {
console.log('Response from server', response);
// Return a promise
return response || $q.when(response);
},
responseError: function(rejection) {
console.log('Error in response ', rejection);
// Continue to ensure that the next promise chain
// sees an error
// Can check auth status code here if need to
// if (rejection.status === 403) {
// Show a login dialog
// return a value to tell controllers it has
// been handled
// }
// Or return a rejection to continue the
// promise failure chain
return $q.reject(rejection);
}
};
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('MyLoggingInterceptor');
}]);
相关文章:
- 从桌面读取python文件时高亮显示代码
- 如何将函数包装在函数中以避免代码重复
- 通过单击表单中的按钮,在代码生成中使用javascript生成字母数字代码
- 货币代码为欧元-金额的格式不应包含小数
- Regex代码只允许一个空格
- 如何将屏幕分辨率乘以 80%,然后在代码中使用
- 从var向代码隐藏函数传递值
- 如何动态插入jquery代码
- 如何在php变量中嵌入JQuery代码
- 代码不会验证
- 如何从rails中的代码中删除新行( )
- Angularjs代码未在匿名函数中运行
- 如何做到这一点,使代码在不传递条件后执行函数
- 如何在读取XLS/XLSX本地文件时,使用IE的javascript代码启用未标记为安全的ActiveX控件
- 面向对象的Javascript代码在IE7中不起作用
- 将 jQuery 代码添加到 Index.aspx 页面
- 如果 angularjs 中的状态代码为 403,请注销
- 通过浏览器关闭/注销时的 JavaScript 代码
- php注销重定向头中断代码
- JQuery登录如果语句代码工作不正常则注销