I am developing a login application, in which I have angular communicating with REST interface for authenticating a user. I am usin $http for this task. Now, I need to redirect my page to another URL(this may be on same or different domain). Also, I need to set the headers during this process.
Please help me with an implementation in order to proceed with this task.
1) AngularJs was designed to build SPAs, you should not redirect to another url. You should redirect to another path in your current page instead. If you are using angular router, you would redirect to another state. Take a look at this for more information: single page application deep linking with login page
2) Because the browser automatically handles 302 responses and forces your ajax function to send another ajax request to the Location to retrieve the final result with status 200. Your server should return 401 instead when the user is not authorized. Cannot handle 302 redirect in ajax and why?
A sample code on client side to handle 401 status code (Unauthorized):
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
if (error.status == 401) { // check for 401 status code
$state.transitionTo("login", { returnUrl: $location.url() });
}
})
Another sample code with $http, I recommend doing it globally inside interceptors
$httpProvider.interceptors.push(function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 404){
$location.path('your redirection path');
}
return $q.reject(response);
}
};
});
3) In order to set your request headers, you could set it globally in your $httpProvider.defaults.headers or per request
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With