AngularJS简单的auth拦截器

时间:2015-06-21 13:30:13

标签: ajax angularjs http angular-http-interceptors

我想在每次发出请求时传入标头我的标记。我现在的方式是使用:

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

我怎么能这样做才能发送到每个请求,当它抛出错误时应该做一个

$state.go('login')

1 个答案:

答案 0 :(得分:2)

如果您想将令牌添加到每个请求中并回复任何错误,最好的办法是使用Angular HTTP拦截器。

根据您的需要,它可能看起来像这样:

$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);
    }

  };
});

希望这有帮助。

相关问题