我一直在试图拦截401响应,当我点击一个API,但它一直令人沮丧地不工作。不能拦截401角
当我访问一个特定的链接时,在浏览器控制台上,我可以看到它使用401响应。基本上我想在它遇到这样的响应时将它重定向到我的登录页面。我在这里看到很多问题,并试图做类似的事情,但它不起作用。
这是我的main.js文件的内容。
var app = angular.module('strelsau_client', ['ngRoute', 'ngResource', 'angularCSS']).config(function ($provide, $httpProvider) {
// Intercept http calls.
$provide.factory('MyHttpInterceptor', function ($q) {
return {
// On request success
request: function (config) {
console.log(config); // Contains the data about the request before it is sent.
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError: function (rejection) {
console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response: function (response) {
console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failture
responseError: function (rejection) {
console.log(rejection); // Contains the data about the error.
// Return the promise rejection.
return $q.reject(rejection);
}
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');
});
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/bookings/fare.html',
controller: 'BookingsCtrl',
css: ['../assets/css/stylesheet.css']
})
.when('/admin',{
templateUrl:'views/admin/index.html',
controller: 'AdminCtrl',
css: ['../assets/css/vendor.css','../assets/css/flat-admin.css']
})
.when('/admin/taxis',{
templateUrl:'views/admin/taxis.html',
controller: 'AdminCtrl',
css: ['../assets/css/vendor.css','../assets/css/flat-admin.css']
})
.when('/admin/customers',{
templateUrl:'views/admin/customers.html',
controller: 'AdminCtrl',
css: ['../assets/css/vendor.css','../assets/css/flat-admin.css']
})
.when('/admin/set_price', {
templateUrl: 'views/admin/set_price.html',
controller: 'AdminCtrl'
})
.when('/admin/adddriver', {
templateUrl: 'views/admin/add_taxi_driver.html',
controller: 'AdminCtrl'
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'AccountCtrl'
})
.otherwise({
redirectTo: '/'
});
});
你忘了在* responseError *中测试401错误以便重定向吗?注意:您可以使用$ httpProvider.interceptors.push({[object]]),而不是在没有其他目的的角度内创建工厂。 – Walfrat
@Walfrat对不起,但我真的不明白你在说什么。没有一个console.log显示任何东西。 –
尝试'$ httpProvider.interceptors.push({responseError:function(reject){console.log(reject); return $ q.reject(reject);}});' – Walfrat