我一直在試圖攔截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