I have created http interceptors and attached to my main app as below:
angular.module('app',['ui.router'])
.factory('AuthInterceptor',function($window,$q){
return{
request: function(config){
console.log("config object is");
console.log(config);
if($window.sessionStorage.getItem('token')){
config.headers['x-access-token']= $window.sessionStorage.getItem('token');
}
return config || $q.when(config);
},
response: function(response){
console.log("response object is:");
console.log(response);
if (response['status'] >= 400) {
console.log("Not Authorized.kindly login first");
$state.transitionTo('login');
}
return response || $q.when(response);
}
};
})
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
});
On the server-side (some express code) I am checking if the user is authorized or not and if not I respond with the following code (only displaying a subset of code to keep things concise):
if(!req.user){
res.send('Not authorized',400);
}
The server code works fine (i can see it in the network tab of the chrome developer tools)
However AuthInterceptor.response() does nto get called.
However do note that the AuthInterceptor.response() does get executed when the response status is 200
So I am confused.. why is it not intercepting 400 statuses ?
If the response status code is outside of the range [200-299], then the responseError interceptor is called.
You need to provide a responseError interceptor:
return {
request: function (config) {...},
responseError: function (rejection) {...}
};
Related
I'm trying to create an Angular 1 app on top of a SAML secured backend.
When I issue a REST request while not authenticated, I get a response with status 200 and an HTML page that will submit a page to the IDP.
I don't want this 200 response to reach my $http(...).then(function(...){}) method in my services.
So I want to change the 200 to a 401 status code in an HTTP interceptor.
Is that possible?
Any alternatives are welcome.
Ok, I found it:
In the response method, you can use this statement to set the status to 401:
return $q.reject({status: 401, error: 'UNAUTHORIZED'});
Full code-sample:
interceptor = function ($q, $location, $rootScope) {
return {
request: function (config) {
...
return config || $q.when(config);
},
requestError: function (rejection) {
return $q.reject(rejection);
},
response: function (response) {
if (response.status === 200 &&
response.headers()['content-type']==='text/html' &&
response.data.startsWith("<HTML><HEAD><TITLE>SAML HTTP Post Binding</TITLE>")) {
//WE HAVE A SAML AUTH REQUEST
return $q.reject({status: 401, error: 'UNAUTHORIZED'});
}
return response;
},
responseError: function (rejection) {
...
}
};
};
$httpProvider.interceptors.push(interceptor);
I have an angular application making async requests to an API service. Since a lot of the resources are protected on the API Service, I need to intercept the HTTP requests made to the service. But as far as I can see, the interceptor I have defined only intercept page load requests.
Here is an experimental setup I have come up with to illustrate my problem:
myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
response: function(response) {
console.log(response);
return response;
}
};
});
});
What I am able to see is that, the interceptor intercepts all calls except the API call as you can see from the attached screen shot showing the console output.
The console output, as you can see from the screen shot below, contains the responses logged when the partial templates have been loaded but not when the GET request was made to the API service.
Why does this happen?
Update
I have changed my setup to include all possible combinations of requests and responses now:
$httpProvider.interceptors.push(function() {
return {
request: function(request) {
console.log(request);
return request;
},
requestError: function(request) {
console.log(request);
return config;
},
response: function(response) {
console.log(response);
return response;
},
responseError: function(response) {
console.log(response);
return response;
}
};
});
Now the interceptor intercepts the message but weirdly shows the status of the caught responseError as:
status: -1
although it clearly is a 401.
Update 2
As it turns out, even 401 responses require the CORS header to be added to it. The problem came up since the REST API I was calling used Spring-CORS library which does not include CORS headers on 401 and 403 responses.
It's a cross-site domain issue because although your using localhost your API call domain is different to the UI's (port 8080 & 8081), have a read of this article for more information. You will need add this header in your webserver:
Access-Control-Allow-Origin: http://foo.example
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I am using the following to show a loading screen whenever I am performing a http request however sometimes if there is an error then it will stay loading (because of the backdrop the app becomes unusable). Rather than hide it on every error checker I was wondering if it is possible to call the timeout after 5 seconds?
.config(function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
$rootScope.$broadcast('loading:show')
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
})
})
Following Jess's answer it now looks like this :
.config(function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
$rootScope.$broadcast('loading:show')
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
},
responseError: function(response) {
$rootScope.$broadcast('loading:hide')
return response
},
requestError: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
})
})
However I cannot seem to be able to put an alert in the requestError to inform the user.
Question
How can I implement an alert to notify the user of the error that has occurred?
try adding responseError and requestError so like this:
responseError: function(responseError) {
$rootScope.$broadcast('loading:hide')
return responseError
and do this again with requestError,
This is from the angular http interceptors docs
requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
Edit to answer comment:
so if you want to throw a alert on responseError than a add a $rootScope.$broadcast('response:error')
in the responseError function
then in the controller you want to throw the alert in just do a
$scope.$on('response:error', function(){throw the error here});
you can also do the same for requestError
this works because $broadcast -- dispatches the event downwards to all child scopes
I have an angularjs project. I am just wondering, how to show the user a message, if a requested view/partial is not found (HTTP 404). At the moment, angular starts the request and gets a 404 response including the error-html, but the user doesn't see any change to the website.
Add an $http interceptor (scroll down on this page) for 'responseError'
angular.module("app").config(function($provide, $httpProvider) {
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'responseError': function(response) {
if (response.status == 404) {
// user hit a 404 -- you can check response.url to see if it matches
// your template directory and act accordingly
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
});
So I have a bunch of controllers that do $http requests
but in every $http request i have a .error(function(data...){//always the same})
How could I build an.. "abstract class" for $http?
This here would be the always repeating code
.error(function(){
$scope.flashes = {
server: {
type: "danger",
message: "There was a server error processing your request. Please try again later."
}
};
})
I add the same concern few weeks ago and i came up with this solution :
I first created a custom service intercepting every http requests made :
.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// 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 failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array. If the intercept param is missing or set to true, we display a modal containing the error
if (rejection.config && typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
}]);
I also defined a custom config property 'intercept' that i can add to the $http config object. It is useful when I don't want to apply this behavior on a particular request.
E.g :
var registerResource = $resource('/registration/candidate/register', {}, {query:
{method:'POST', isArray: false, intercept: false }
});
In order the have a flexible solution, it is also important to not forget to do :
return $q.reject(rejection);
So you can still use the error callback on your promise in your controller if you want to combine both ways (interception + manual handling)
Finally, I added this service to my application :
app.config(['$httpProvider', function($httpProvider) {
// Add the interceptor to the $httpProvider to intercept http calls
$httpProvider.interceptors.push('HttpInterceptor');
}]);
I simplified the service but you can also use it for many things. Personally, I also use it to :
Make sure to not fire duplicate http requests (if the user click a lot on a submit button).
Draw an alert at the beginning of an http call and close it at the end to inform the user that is treatment is processing (export of data for instance).
PS: The official documentation mention this interceptor
You could do something like this:
app.service('myHttp', function($http){
return function($scope, httpParameters){
var httpPromise = $http(httpParameters);
httpPromise.error(function(){
$scope.flashes = {
server: {
type: "danger",
message: "There was a server error"
}
}
});
};
});
app.controller('MainCtrl', function($scope, myHttp) {
myHttp($scope, {method: 'GET', url: 'www.google.com'});
});