AngularJS 简单的身份验证拦截器

AngularJS simple auth interceptor

我想在每次发出请求时传递 headers 我的令牌。我现在的做法是使用:

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

我该怎么做才能将其发送到每个请求,并且当它抛出错误时它应该执行

$state.go('login')

如果您想将令牌添加到每个请求并响应任何错误,最好的办法是使用 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);
    }

  };
});

希望对您有所帮助。