如何向 openlayers4 请求添加 http 标头?

eri*_*ire 4 openlayers

某些 wms 或 wfs 源需要用户和密码身份验证。例如https://apps.sogelink.fr/maplink/public/wfs?request=GetCapabilities 需要基本身份验证。如何注入此身份验证?

dub*_*ube 5

您可以将自己的提供imageLoadFunctionImageWMS 源。默认的只是获取 URL 并将其作为 img 标签的 src 插入:

ol.source.Image.defaultImageLoadFunction = function(image, src) {
  image.getImage().src = src;
};
Run Code Online (Sandbox Code Playgroud)

OpenLayers GitHub 上已经提出了这个问题,这里有一个例子:

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();
}
Run Code Online (Sandbox Code Playgroud)

OpenLayers 的文档非常好。只需找到一个使用您想要的功能的示例,然后点击 API文档的链接即可。ol.source.Vector文档甚至包括 WFS 加载函数的示例,您可以在其中操作请求:

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