Angular Js - set token on header default

风格不统一 提交于 2019-11-26 09:43:23

问题


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.

Here is how I add the token:

app.factory(\'api\', function ($http, $cookies) {
return {
    init: function (token) {
        $http.defaults.headers.common[\'Token\'] = token || $cookies.loginTokenCookie;
    }
  };
});

Which gets called from here:

app.run(function ($cookies, $http, $location, $rootScope,api) {
    $rootScope.location = $location;
    api.init();
});

I have tried doing it like the following:

app.factory(\'api\', function ($http, $cookies) {
return {
    init: function (token) {
        $http.defaults.headers.common[\'Token\'] = token || $cookies.loginTokenCookie;
        $http.defaults.headers.post[\'Token\'] = token || $cookies.loginTokenCookie;

    }
};
});

But this also doesnt work. It only works when I change the header key name like the following:

 $http.defaults.headers.post[\'Token-Post\'] = token || $cookies.loginTokenCookie;

How do I assign a default header to posts and get requests in AngularJs?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/23244809/angular-js-set-token-on-header-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!