如何为 mapbox-gl-js 中的来源指定授权 Header?

How to specify Authorization Header for a source in mapbox-gl-js?

如何使用 mapbox-gl-js 为 wms 源设置请求 header?我需要所有磁贴请求来添加一个 header,看起来像:

Authorization: "Bearer base64-encoded-token"

WMS example, map#addSource and map#addLayer 让我相信无法设置磁贴请求 headers。

您现在可以使用 transformRequest 选项添加自定义 header:

A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with a url property and optionally headers and credentials properties.

示例:

const map = new mapboxgl.Map({
  container: 'map',
  center: [2.35, 48.86],
  zoom: 13,
  transformRequest: (url, resourceType) => {
    if (resourceType === 'Source' && url.startsWith('http://myHost')) {
      return {
        url: url,
        headers: { 'Authorization': 'Bearer ' + yourAuthToken }
      }
    }
  }
});