SuperMap二维iClient客户端如何添加自定义请求头(一)

作者:刘大

本文已同步更新于简书文章https://www.jianshu.com/p/79f9394d4b45

在项目实际应用中,有时候需要在发送请求中添加一些自定义的请求头,那现在来看看SuperMap二维iClient客户端中是如何是使用的捏

1.版本支持情况

二维iClient for Leaflet/Openlayers/MapboxGL 从SuperMap iClient 10i版本起就支持增加。

2.使用前准备

由于SuperMap iServer中有设置的允许的请求头参数名配置,在前端设置请求头前,需在iServer解压目录\webapps\iserver\WEB-INF\web.xml中的cors.allowed.headers增加value,譬如,现在我们需要增加token,apptoken这两个自定义参数,则需按照下图添加

<init-param>
		<param-name>cors.allowed.headers</param-name>
		<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token,apptoken</param-value>
 </init-param>

如果不进行配置,在前端请求时,会看到如下错误:
image.png

Tips:token这个自定请求头在SuperMap iServer10i的版本后,iServer会进行解析,验证的是用户的令牌(当该服务进行授权,需通过token令牌验证是否有权限访问该服务。所以自定义自己的请求头时,不要以token为名
3. iClient for Leaflet/Openlayers/MapboxGL具体使用
3.1和iServer有交互的功能的service接口都可添加headers

即以 L.supermap.*service(Leaflet),ol.supermap.*service(Openlayers),mapboxgl.supermap.*service(MapboxGL)接口都支持headers,Classic无此参数,可使用下面的全局设置

#Leaflet
L.supermap
	.featureService(url,{
    
    headers: {
    
    
		apptoken: '...'
	}})
	.getFeaturesByGeometry(geometryParam, function (serviceResult) {
    
    });
}

#Openlayers
ol.supermap
	.featureService(url, {
    
    headers: {
    
    
		apptoken: '...'
	}})
	.getFeaturesByGeometry(geometryParam, function (serviceResult) {
    
    });
}

#MapboxGL
mapboxgl.supermap
    .featureService(url, {
    
    headers: {
    
    
		apptoken: '...'
	}})
	.getFeaturesByGeometry(geometryParam, function (serviceResult) {
    
    });
}
3.2 全局设置

在与iServer的服务交互的功能前,重写下面的方法带上自定义请求头token,进行全局设置

#  iClient for Leaflet/Openlayers/MapboxGL
SuperMap.FetchRequest.commitbak = SuperMap.FetchRequest.commit;
SuperMap.FetchRequest.commit = function (method, url, params, options) {
    
    
	options.headers = options.headers || {
    
    
		token: '42f_WTvu4du_QouTxU9C6qSRiQml38DVN2vXyjOT-wbhYwfKu1qKqA6_fvAW_I_cC1Zthpgeb7gxOxbpyeATsQ..'
		}
	return SuperMap.FetchRequest.commitbak(method, url, params, options)
		}
#Classic
SuperMap.Util.commit= SuperMap.Util.committer;
SuperMap.Util.committer = function (options) {
    
    
    options.headers = options.headers || {
    
    
        token: '42f_WTvu4du_QouTxU9C6qSRiQml38DVN2vXyjOT-wbhYwfKu1qKqA6_fvAW_I_cC1Zthpgeb7gxOxbpyeATsQ..'
        }
    return  SuperMap.Util.commit(options)
        }
Tip:Classic中,和iSever所以域不是同一域的话,会请求jsonp格式,但是jsonp请求实质是嵌入

方式:isInTheSameDomain设置为true

 getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url2, {
    
    
            eventListeners: {
    
    "processCompleted": processCompleted, "processFailed": processFailed},
            isInTheSameDomain:true
        });

这篇主要介绍和iserver交互的功能接口添加请求头,在下一篇会详细介绍地图瓦片如何添加

猜你喜欢

转载自blog.csdn.net/supermapsupport/article/details/112261598