Using AngularJs in order to retrieve a header from the response and set it on all requests

前端 未结 2 1481
孤城傲影
孤城傲影 2020-12-20 00:59

I am trying to use Angularjs in order to retrieve the csrf token from one of the response\'s header and set it on all requests.

I h

相关标签:
2条回答
  • 2020-12-20 01:49

    I think you can do it like this in config function:

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
        $httpProvider.interceptors.push(function() {
            return {
                response: function(response) {
                    $httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
                    return response;
                }
            }    
        });
    }]);
    
    0 讨论(0)
  • 2020-12-20 01:52

    You can use the same interceptor to intercept any request generating from your application and inject the token into it. For example:

    .factory('csrfResponseInterceptor', [function () {
            var token = null;
    
            return{
                request: function(config){
                    if(token){
                       config.headers['X-CSRF-TOKEN'] = token;
                    }
                    return config;
                },
                response: function(response){
                    token = response.headers('X-CSRF-TOKEN');
                    return response;
                }
            }
        }])
    
    0 讨论(0)
提交回复
热议问题