我尝试使用openlayers 4.6和angular 5加载WMS图像层,代码为:
const syr_layer = new ol_layer_Image({
source: new ol_source_ImageWMS({
url: 'serverurl', crossOrigin: 'anonymous', serverType: 'geoserver',
params: { 'LAYERS': 'tst:syr'},
projection: 'EPSG:4326'
});
});
但它引发了一个错误:
GET(myserverurl)401(在。中找不到身份验证对象) SecurityContext的)
如何使用openlayers发送的GET请求发送身份验证标头?
答案 0 :(得分:2)
就您而言,您可能希望使用tileLoadFunction
ol.source.ImageWMS
(API doc)
为了说明,您可以在下面看。 2"秘密"是customLoader
并且要进行身份验证以取消注释req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
<!DOCTYPE html>
<html>
<head>
<title>Tiled WMS</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
function customLoader(tile, src) {
var client = new XMLHttpRequest();
client.open('GET', src);
// Uncomment to pass authentication header
//req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
client.onload = function() {
tile.getImage().src = src;
};
client.send();
}
var layers = [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
tileLoadFunction: customLoader,
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
</script>
</body>
</html>
答案主要是从How to add a http header to openlayers3 requests?借来的,但由于所提供的语法不起作用而进行了一些调整。
答案 1 :(得分:1)
感谢@Thomas,你的回答是不正确的100%,但它清楚了我得到正确答案的方式。
这是适用于我的tileLoader
函数:
private tileLoader(tile, src) {
const client = new XMLHttpRequest();
client.open('GET', src);
client.responseType = 'arraybuffer';
client.setRequestHeader('Authorization', 'Basic ' + btoa(user + ':' + pass));
client.onload = function () {
const arrayBufferView = new Uint8Array(this.response);
const blob = new Blob([arrayBufferView], { type: 'image/png' });
const urlCreator = window.URL || (window as any).webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
tile.getImage().src = imageUrl;
};
client.send();
}