简体   繁体   中英

Control of headers in a $http request

I am struggle with header caching in a request.

my resource is looks like:

method: 'GET',
cache: false,
headers: {
  session: auth.mySession()
}

Provider is also configured.

config(['$httpProvider', function($httpProvider) {
 if (!$httpProvider.defaults.headers.get) {
  $httpProvider.defaults.headers.get = {};
 }
 $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
 $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
 }]).

In practice it doesn't work. Request is sent with a session while it is removed and without the session while it's set. I had to press Ctrl+F5.

At last I realized that it is not about caching results, but caching headers themselves.

Headers are calculated just once at page initialization stage. Right after that fact I came with an interceptor solution, which always injects valid session into a request's header.

config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('injectingSessionInterceptor');
}]).
service('injectingSessionInterceptor', ['auth', function (auth) {
    var ser = this;
    ser.request = function (config) {
        var session = auth.mySession();
        config.headers.session = session;
        return config;
    };
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM