Angular Js - set token on header default

后端 未结 2 767
太阳男子
太阳男子 2020-11-29 06:42

Im trying to add a header with my access token to each API call. It works well for all the GET requests, but as soon as I try to make a POST the header isn\'t added.

<
相关标签:
2条回答
  • 2020-11-29 07:25

    Maybe I'm wrong but why not just:

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.post['token'] = 'your_token';
    }]);
    

    Interceptors are heavier and not needed in this case

    0 讨论(0)
  • 2020-11-29 07:29

    Instead of placing the token on the headers inside each service (or call), it might be better to use an $http interceptor (docs here).

    Then, you can place the token on every request. This will work whether the request is a GET or POST.

    JS sample:

    $httpProvider.interceptors.push(function($q, $cookies) {
        return {
         'request': function(config) {
    
              config.headers['Token'] = $cookies.loginTokenCookie;
              return config;
          }
        };
      });
    
    0 讨论(0)
提交回复
热议问题