Add HTTP Header in JavaScript to requests for images

angularjs, javascript

Solution

In Angular 1.2.X

There are more than a few ways to do this. In Angular 1.2, I recommend using an http interceptor to "scrub" outgoing requests and add headers.

// An interceptor is just a service.
app.factory('myInterceptor', function($q) {
  return {
    // intercept the requests on the way out.
    request: function(config) {
      var myDomain = "http://whatever.com";

      // (optional) if the request is heading to your target domain,
      // THEN add your header, otherwise leave it alone.
      if(config.url.indexOf(myDomain) !== -1) {

        // add the Authorization header (or custom header) here
        config.headers.Authorization = "Token 12309123019238";
      }

      return config;
    }
  }
});

app.config(function($httpProvider) {
  // wire up the interceptor by name in configuration
  $httpProvider.interceptors.push('myInterceptor');
});

In Angular 1.0.X

If you're using Angular 1.0.X, you'll need to set the headers more globally in the common headers... `$http.defaults.headers.common.Authentication`

EDIT: For things coming from

For this you'll need to create a directive, and it's probably going to get weird.

You'll need to:

- Create a directive that is either on your `<img/>` tag, or creates it.

- Have that directive use `$http` service to request the image (thus leveraging the above http interceptor). For this you're going to have to examine the extension and set the proper content-type header, something like: `$http({ url: 'images/foo.jpg', headers: { 'content-type': 'image/jpeg' }).then(...)`

- When you get the response, you'll have to take the raw base64 data and set the `src` attribute of your image element to a data src like so: `<img src="data:image/jpeg;base64,9hsjadf9ha9s8dfh...asdfasfd"/>`.

... so that'll get crazy.

If you can make it so your server doesn't secure the images you're better off.

Problem

I have a JS/HTML5 Project based on angularjs where I protect the api with an authorization token set in the http header. Now I also want to protect the access to images from the server. I know how to do it on the server side, but how can I add HTTP Headers to image requests in angular or javascript? For api request we have already added it to the services ($ressource) and it works.

Original source

Related problems