AngularJS Adding a header to the $http.get

2019-07-27 02:29发布

问题:

I'm trying to add the 'Authorization' header containing a token for future HTTP request. Retrieval of the token seems to be fine however when making a get request it fails with an Unauthorized error message. After checking the request headers Authorization header does not exist in the request block...

window.crUtil = /*window.crUtil ||*/ (function() {

    // Angular Services
    var $injector = angular.injector(['ng']);
    var $http = $injector.get('$http');


    // getting the CFF data
    function get_data() {
    		getJWTAWS();
        var url = '/AWS/getDATA/555';
				console.log('AUTH header before call: ' + $http.defaults.headers.common.Authorization);
        $http.get(url,httpHeader).then(function successCallback(response) {
            var data = response.data;
            var cff = initCff();
            alert(data.itemId);
            
        }, function errorCallback(response) {
            initCff();
            alert("Error while getting data ");
        });

    }
		
    function getJWTAWS() {
        var httpConfig = {
            cache: true, 
            params: {}
        };

        $http.get('/AWS/token', httpConfig).then(
            function(response) {
                if (response.data.accessToken) {
                    // add jwt token to auth header for all requests made by the $http service

                    $http.defaults.headers.common.Authorization = response.data.tokenType + ' ' + response.data.accessToken;
                }
            },
            function(error) {
                alert('jwt token could not be retrieved.');
            }
        );
    }


})();

var result = util.get_data();
console.log ('called search function ' + result);

Function getToken() returns a value but as I'm new on that topic I'm not quite sure if the way I added the token to the headers is proper. Could you please advise on the proper way to include the headers in the request. I also tried to add it to the get request like $http.get(URL,httpHeaders)... but it also didn't work.

回答1:

I'm not sure I understand your problem completely as you did not provide what you call

httpConfig

If you're struggling to declare the headers, try making the get request like this:

$http({
  method: 'GET',
  url: YOUR_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': AUTH_STRING_HERE
  }
}).then(function (response) { ... });

You can add any headers you like in the headers object there.



回答2:

Try adding this in your config block and set the token in your rootscope

$httpProvider.interceptors.push({
    request: function (config) {
        config.headers.Authorization = $rootScope.token;
        return config;
    }
})