请求传参时encodeURIComponent将空数组转换为空
问题描述:
后台需要接受一个空数组[]作为参数,前端请求前将字段值设置为[],但是发送请求后,参数转化为空了
前端请求前赋值为空数组:this.voucher.userAccounts = []
参数打印出来:
发送请求后:
造成的原因:
在前端axios对请求参数做了转换:
// 请求参数转换
transformRequest: [function (data, headers) {
let ret = ''
for (let it in data) {
if (ret !== '') ret += '&'
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
}
return ret
}]
解决办法:
- 修改axios的配置:
// 请求参数转换
transformRequest: [function (data, headers) {
let ret = ''
for (let it in data) {
if (ret !== '') ret += '&'
if (Object.prototype.toString.call(data[it]) === '[object Array]' && !data[it].length) {
ret += encodeURIComponent(it) + '=' + '[]'
} else {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
}
}
return ret
}]
-
赋值为空数组字符串:
this.voucher.userAccounts = ‘[]’