【问题标题】:How to add a http header to openlayers4 requests?如何向 openlayers4 请求添加 http 标头?
【发布时间】:2018-03-04 12:01:16
【问题描述】:

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

【问题讨论】:

标签: openlayers


【解决方案1】:

您可以将自己的imageLoadFunction 提供给ImageWMS 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 文档甚至包含 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....
  }
}); 

【讨论】:

  • 你好cmets发帖很困难,因为字数有限,加评论框也很少。而且我再也无法输入格式化代码了。复制过去有时会删除换行符。简而言之,我不知道如何轻松地做到这一点。我会尝试拆分我的评论。
  • 我已经看到了这个答案,但我不知道如何在这里应用它,然后它只涉及 wms,wfs 呢?
  • 我的尝试://image dict var imagedict = new ol.layer.Image({ title: 'dict raster', opacity: 1.0, source: new ol.source.ImageWMS({ url: ' apps.sogelink.fr/maplink/public/wms?request=GetCapabilities', 参数: {FORMAT: 'image/png'}, imageLoadFunction: function customLoader(tile, src)
  • { var client = new XMLHttpRequest(); var user = 'sig@inrapdirmed.fr'; var pass = '#####'; client.open('GET', src); //client.setRequestHeader('foo', 'bar'); client.setRequestHeader("授权", "基本" + btoa(user + ":" + pass));
  • client.onload(function() { var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText))); tile.getImage().src = 数据;});客户端.send(); } }) });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多