1

I am using Angular JS to get an image from the Server using Authorization: Bearer token. I have already gone through the example at Loading Image in JavaScript with Bearer token.

I have used the code like,

var request = new XMLHttpRequest();
request.open('GET','https://dl.content.com/contentfile.jpg', true);
request.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token);
request.responseType = 'arraybuffer';
request.onload = function(e) {
    var data = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null, data);
    var base64 = btoa(raw);
    var src = "data:image;base64," + base64;

    document.getElementById("image").src = src;
};

request.send();

It works fine. But it is written in plain JavaScript. I just want to know if there is any equivalent syntax using Angular JS to achieve the same thing?

I have tried using $http of Angualar JS to do it. My code is like below,

$http({
            method: 'GET',
            url: file,
            headers: {
                'Authorization': 'Bearer ' + Constants.token
            }
        }).then(function (data) {
            console.log('from backend', data)
        })

But it gives the following error and browser gets hanged.

Error Screenshot Error Screenshot

I don't know why the error is occurred and how to fix it.

Anijit Sau
  • 555
  • 2
  • 8
  • 25

1 Answers1

0

what I usually do is use an interceptor for the request that I made.

 $httpProvider.interceptors.push('myInterceptor');

and use a factory to work on request and response.

.... .factory('myInterceptor', function() {
return {
    request: function(config) {
        config.headers.Authorization="Bearer "+ myberer
        return config;
    },
    requestError: function(reject) {
      // do something on error
      console.log('request Error')
    },
    response: function(config) {

    },
    responseError: function(reject) {
    }
};

you can find more infos on this article http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

or searching about angularJs interceptor

icchio
  • 109
  • 2
  • 13