Reputation: 499
My question is about $resource
's interceptor(responseError). I want to emphasize that the angularjs I based on is V1.3.6
.
Problem:
app.factory('authInterceptor',['$q', '$location', '$log', function($q, $location, $log){
$log.debug('this is a regular factory with injection');
return {
responseError: function(response){
console.log(response)
// problem is that I cant check 401 by response.status,
// because the response here is AN ERROR OBJECT like `SyntaxError: ...`. Anyway to get the status?
return $q.reject(response);
}
}
}])
When I get 401 response, responseError
's arguments is AN ERROR OBJECT like SyntaxError: Unexpected token U
because the reponse from server is plain text Unathorized
with status 401
.
But I want to get the response.status
, and do something if it is 401
.
Any help will be appreciated.
Upvotes: 1
Views: 1521
Reputation: 499
This question should be closed because I finally found answer myself.
When response is 401/404 and anything besides 200, transformResponse
still executed and an error occurred! This error just cover the normal response(has status property), so I never get the original response inside interceptor!
I think it's stupid to execute transformResponse
if the response's status is not 200! And inside transformResponse
, you can't access status code...
Upvotes: 4
Reputation: 413
Here is a simple interceptor that handles 401s, as well does some configuration:
angular.module('notesApp', [])
.factory('AuthInterceptor',['AuthInfoService', '$q', function(AuthInfoService, $q) {
return {
responseError: function(responseError) {
if (responseError.status === 401) { // authentication issue
//redirect user to login or do something else...
}
return $q.reject(responseError);
}
};
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
}]);
** Here is an interceptor that only intercepts incoming responses with a non-200 status code.** If the status code is 401, the user is redirected to the login page. In this case, the promise is rejected so that the controller or service still sees a failure
Upvotes: 0