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
490 views
in Technique[技术] by (71.8m points)

openlayers - How to add a http header to openlayers4 requests?

some wms or wfs sources require user and password authentication. for example https://apps.sogelink.fr/maplink/public/wfs?request=GetCapabilities need Basic authentication. How can I inject this authentication?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can provide your own imageLoadFunction to an ImageWMS source. The default one just takes the URL and inserts it as the src of the img tag:

ol.source.Image.defaultImageLoadFunction = function(image, src) {
  image.getImage().src = src;
};

That question was already asked on the OpenLayers GitHub, here is an example from there:

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

The documentation of OpenLayers is really good. Just find an example that uses features you want and then follow the links to the API docs.The ol.source.Vector doc even includes an example of a loading function for WFS, where you could manipulate the request:

new ol.source.Vector({
  format: new ol.format.GeoJSON(),
  loader: function(extent, resolution, projection) {
    var wfsUrl = 'TODO';
    var xhr = new XMLHttpRequest();
    // see above example....
  }
}); 

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

...