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

问题描述 投票:2回答:1

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

openlayers
1个回答
2
投票

你可以提供自己的imageLoadFunctionImageWMS source。默认值只是获取URL并将其作为img标记的src插入:

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

那个问题是already asked on the 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();
}

OpenLayers的文档非常好。只需找到一个使用您想要的功能的示例,然后按照指向API文档的链接进行操作.ol.source.Vector doc甚至包含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....
  }
}); 
© www.soinside.com 2019 - 2024. All rights reserved.