如何让options对象path中的日期以双引号包裹输出?
问题描述
我在createOptionsFor方法中创建options对象,使用console.log打印时,path里&SUBSET=ansi(部分的日期是单引号包裹的格式:&SUBSET=ansi('2019-10-05'),我需要实现日期用双引号包裹的效果:&SUBSET=ansi("2019-10-05")。
之前尝试拼接字符串codeDERes.SUBSET_TIME + '"'+startDate+'"' + ')',但打印后结果变成了&SUBSET=ansi(%222019-10-05%22),双引号被URL编码成了%22,求解决方法。
相关代码片段
options对象代码
createOptionsFor(rasDaManLayer, startDate, wktEPSG32632, userName, password) { return this.options = { agent: this.agent, auth: userName + ':' + password, protocol: codeDERes.PROTOCOL_HTTPS, host: codeDERes.HOST, path: encodeURI( codeDERes.PATH +codeDERes.SERVICE +codeDERes.VERSION +codeDERes.REQUEST +codeDERes.COVERAGE_ID + rasDaManLayer +codeDERes.SUBSET_TIME + '''+startDate+''' + ')' +codeDERes.SUBSET_CRS +codeDERes.CLIP + wktEPSG32632 +codeDERes.OUTPUT_CRS +codeDERes.ENCODE_FORMAT_IMAGE +codeDERes.RANGE_SUBSET ), method:'GET', headers: { 'Content-Type': 'application/json' } }; }
常量定义代码
function define(name, value) { Object.defineProperty(codeDERes , name, { value: value, enumerable: true, writable: false }); } export let codeDERes = {}; define('SUBSET_TIME','&SUBSET=ansi(')
解决方案
问题根源是encodeURI会把双引号"自动编码为%22。要保留双引号,有两种可行的修改方式:
方式一:单独编码动态参数(推荐)
不对整个path字符串做整体编码,只对其中的动态变量(比如图层名、日期、WKT坐标)单独用encodeURIComponent处理,这样既能保证特殊字符被正确转义,又能保留我们需要的双引号格式。
修改后的代码:
createOptionsFor(rasDaManLayer, startDate, wktEPSG32632, userName, password) { // 单独编码动态参数,避免整体编码转义双引号 const encodedLayer = encodeURIComponent(rasDaManLayer); const encodedDate = encodeURIComponent(startDate); const encodedWkt = encodeURIComponent(wktEPSG32632); return this.options = { agent: this.agent, auth: userName + ':' + password, protocol: codeDERes.PROTOCOL_HTTPS, host: codeDERes.HOST, path: codeDERes.PATH + codeDERes.SERVICE + codeDERes.VERSION + codeDERes.REQUEST + codeDERes.COVERAGE_ID + encodedLayer + codeDERes.SUBSET_TIME + '"' + encodedDate + '"' + ')' + codeDERes.SUBSET_CRS + codeDERes.CLIP + encodedWkt + codeDERes.OUTPUT_CRS + codeDERes.ENCODE_FORMAT_IMAGE + codeDERes.RANGE_SUBSET, method:'GET', headers: { 'Content-Type': 'application/json' } }; }
方式二:编码后替换回双引号
如果必须对整个path做encodeURI编码,可以在编码完成后,把所有被转义的%22替换回双引号:
path: encodeURI( codeDERes.PATH + codeDERes.SERVICE + codeDERes.VERSION + codeDERes.REQUEST + codeDERes.COVERAGE_ID + rasDaManLayer + codeDERes.SUBSET_TIME + '"' + startDate + '"' + ')' + codeDERes.SUBSET_CRS + codeDERes.CLIP + wktEPSG32632 + codeDERes.OUTPUT_CRS + codeDERes.ENCODE_FORMAT_IMAGE + codeDERes.RANGE_SUBSET ).replace(/%22/g, '"'),
说明
encodeURI会对URL中的特殊字符(包括双引号)进行转义,这是符合URL规范的行为,但如果服务端要求必须用双引号包裹日期,就需要通过上述两种方式绕过这个转义,保留原始的双引号格式。
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

