Openlayers: Request headers?

Created on 2 Oct 2015  路  4Comments  路  Source: openlayers/openlayers

How can I inject a http header into every map layer request?

In this case, I need to send an Authentication header for a given layer and source, but I may want to send other headers too.

Most helpful comment

By default, image loading happens like this: img.src = 'http://example.com/tile.png'; - that is, we set the src attribute of an Image to the image url. In this case, you don't have an opportunity to set the headers for the request.

You can override this behavior by calling source.setTileLoadFunction(customLoader). This assumes you are working with a "tile image" source. Then it is your responsibility to define the custom loader. This function will get called with an ol.ImageTile and a string URL.

The rest is up to you. Your custom loader might look something like this:

function customLoader(tile, src) {
  var client = new XMLHttpRequest();
  client.open('GET', src);
  client.setRequestHeader('foo', 'bar');
  client.onload(function() {
    var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText));
    tile.getImage().src = data;
  });
  client.send();
}

All 4 comments

By default, image loading happens like this: img.src = 'http://example.com/tile.png'; - that is, we set the src attribute of an Image to the image url. In this case, you don't have an opportunity to set the headers for the request.

You can override this behavior by calling source.setTileLoadFunction(customLoader). This assumes you are working with a "tile image" source. Then it is your responsibility to define the custom loader. This function will get called with an ol.ImageTile and a string URL.

The rest is up to you. Your custom loader might look something like this:

function customLoader(tile, src) {
  var client = new XMLHttpRequest();
  client.open('GET', src);
  client.setRequestHeader('foo', 'bar');
  client.onload(function() {
    var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText));
    tile.getImage().src = data;
  });
  client.send();
}

Thanks!

We'll initially be using this for WMS and WMS-C, so I'm guessing setImageLoadFunction() is what we'll need to override.

Hi, is this actually working?
I tried writing a customLoader on a layer which doesn't require a header. (and doesn't set any http header)
The result is just empty (return nothing, no error message)

Is there anything that i miss out?

I open the issue again in #5401

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Dovernh picture Dovernh  路  4Comments

nidico picture nidico  路  3Comments

darkscript picture darkscript  路  3Comments

mohawk2 picture mohawk2  路  4Comments

ablakey picture ablakey  路  4Comments