Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting headers and page redirection using angular

Tags:

angularjs

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.

like image 336
Jaspreet Avatar asked Mar 22 '14 12:03

Jaspreet


1 Answers

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

like image 130
Khanh TO Avatar answered Jan 03 '23 15:01

Khanh TO