Setting application wide HTTP headers in AngularJS

前端 未结 3 871
广开言路
广开言路 2020-12-01 02:59

Is there a way to set the $httpProvider headers outside of angular.module(\'myApp\', []).config()?

I\'m getting an Auth-Token from the serv

相关标签:
3条回答
  • 2020-12-01 03:18

    You can use default headers for angular 1.0.x:

    $http.defaults.headers.common['Authentication'] = 'authentication';
    

    or request interceptor for angular 1.1.x+:

    myapp.factory('httpRequestInterceptor', function () {
      return {
        request: function (config) {
    
          // use this to destroying other existing headers
          config.headers = {'Authentication':'authentication'}
    
          // use this to prevent destroying other existing headers
          // config.headers['Authorization'] = 'authentication';
    
          return config;
        }
      };
    });
    
    myapp.config(function ($httpProvider) {
      $httpProvider.interceptors.push('httpRequestInterceptor');
    });
    

    Since factories/services are singletons, this works as long as you do not need to dynamically change your 'authentication' value after the service has been instantiated.

    0 讨论(0)
  • 2020-12-01 03:25
    $http.defaults.headers.common['Auth-Token'] = 'token';
    

    It seems headers() normalizes the key names.

    0 讨论(0)
  • 2020-12-01 03:26

    Adding to above responses of @Guria and @Panga

    config.headers['X-Access-Token'] = $window.sessionStorage.token;
    

    One can use x-access-token in header as JWT(jsonwebtoken). I store JWT in the session storage when a user authenticate first time.

    0 讨论(0)
提交回复
热议问题