都说要把用户输入的内容进行转义,避免不可预知的错误。那么,对于小程序跳转URL通过queryString方式传参,如果不encodeURIComponent转义内容,会发生什么。
一、encodeURIComponent之前
A页面计划传输给B页面的内容:
router:跳转链接,url:图片链接(注意图片链接含有问号?),price:价格
const data = {
router: `/packs/productDetail?skuId=123`,
url:
'https://abc.com/UP4m2bLLIei24w5XUBK.png?GalaxyAccessKeyId=EAKC4WAFZQV4K',
price:100,
};
wx.navigateTo({url: `${data.router}&url=${data.url}&price=${data.price}`});
B页面onLoad里接受到的options参数:
丢失了router字段问号?后面的数据。
二、encodeURIComponent之后
A页面计划传输给B页面的内容:
const data = {
router: encodeURIComponent(`/packs/productDetail?skuId=123`),
url: encodeURIComponent(
'https://abc.com/UP4m2bLLIei24w5XUBK.png?GalaxyAccessKeyId=EAKC4WAFZQV4K'
),
price: 100,
};
wx.navigateTo({url: `${data.router}&url=${data.url}&price=${data.price}`});
encodeURIComponent参数后打印结果:
B页面onLoad里接受到的options参数:
能得到A页面完整的参数
分别对得到的router 和url 进行decodeURIComponent:
{
router: decodeURIComponent(options.router),
url: decodeURIComponent(options.url),
price: 100,
}
打印结果:
深刻的领悟:为了避免服务器收到不可预知的请求,对任何用户输入的作为URI部分的内容你都需要用encodeURIComponent进行转义!