Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angularjs - Angular Js - set token on header default

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...