Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

openlayers 3 - How to add a http header to openlayers3 requests?

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.

A search of the code and docs came up with no clues.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answered on github.

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...