0

I want to pass in the headers my token each time i make a request. the way i do it now is using:

$http.defaults.headers.common['auth_token'] =  $localStorage.token;

How could i do that to make that sent to every request, and when it throws an error it should do a

$state.go('login')
5
  • use it in a run method Docs n google be ur friend docs.angularjs.org/api/ng/service/$http Commented Jun 21, 2015 at 13:33
  • you mean like this .config(function ($httpProvider) { $http.defaults.headers.common['auth_token'] = $localStorage.token; }) what about the $state.go when it errors @swapnesh Commented Jun 21, 2015 at 13:34
  • Or go through this stackoverflow.com/a/27136594/639406 Commented Jun 21, 2015 at 13:36
  • ahh sorry I missed that part..give this tut a shot brewhouse.io/blog/2014/12/09/… Commented Jun 21, 2015 at 13:43
  • @swapnesh is there just a function where i could just do a $state.go if i run $http.defaults.headers.common['auth_token'].. and it fails?? Commented Jun 21, 2015 at 13:50

1 Answer 1

3

If you want to add your token to each request, and respond to any errors, your best bet would be to use an Angular HTTP interceptor.

Subject to your needs, it might look something like this:

$httpProvider.interceptors.push(function ($q, $state, $localStorage) {
  return {

    // Add an interceptor for requests.
    'request': function (config) {
      config.headers = config.headers || {}; // Default to an empty object if no headers are set.

      // Set the header if the token is stored.
      if($localStorage.token) {
        config.headers.common['auth_token'] = $localStorage.token;
      }

      return config;
    },

    // Add an interceptor for any responses that error.
    'responseError': function(response) {

      // Check if the error is auth-related.
      if(response.status === 401 || response.status === 403) {
        $state.go('login');
      }

      return $q.reject(response);
    }

  };
});

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.