- 起因: 在一次项目练习中, 使用axios , post传递参数时, 发现传递错误,
axios在使用时,后台可能接收不到参数:添加链接描述
经人指点后, 知道是参数的格式错误, 需要使用qs.stringify将参数进行格式化的处理.
let url='https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=axios&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_btype=t&inputT=1269&rsv_sug3=24&rsv_sug2=0&rsv_sug4=2649'
let data=qs.parse(url)
console.log(data);
console.log(qs.stringify(data));
结果
Object
f: "8"
https://www.baidu.com/s?ie: "utf-8"
inputT: "1269"
rqlang: "cn"
rsv_bp: "1"
rsv_btype: "t"
rsv_dl: "tb"
rsv_enter: "1"
rsv_sug2: "0"
rsv_sug3: "24"
rsv_sug4: "2649"
tn: "baidu"
wd: "axios"
__proto__: Object
同理使用qs.stringify的时候
将所有对象进行拼接
https%3A%2F%2Fwww.baidu.com%2Fs%3Fie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=axios&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_btype=t&inputT=1269&rsv_sug3=24&rsv_sug2=0&rsv_sug4=2649
手动实现一个qs
(function () {
var qs = {
parse: parse,
stringify: stringify
}
var reg = /(\w+)(\=)?([^=&]+)?/
var regReplace = new RegExp(reg, 'g')
function parse (search, mergeSameKey) {
search = search.replace(/^\?/, '') // ignore start with `?`
var params = {}
search.replace(
regReplace, // ignore empty key, ignore empty key with `=`
function (text) {
var matched = text.match(reg) // [fulltext, key, `=`, value]
var key = matched[1]
var value = matched[3] || '' // maybe undefined
if (mergeSameKey && params[key]) {
if (params[key] instanceof Array) {
params[key].push(value)
} else {
params[key] = [params[key]].concat(value)
}
} else {
params[key] = value
}
}
)
return params
}
function stringify (params) {
var search = []
for (var key in params) {
var item = [key, params[key]]
search.push(item.join('='))
}
return search.join('&')
}
// test case
var s1 = 'a=1&b=2'
var res1 = parse(s1)
console.assert(res1.a === '1', '`a` should be equal 1')
console.assert(stringify(res1) === s1, '`stringify` for restore')
var s2 = '?a=1&b=2&a=3'
var res2 = parse(s2, true)
console.assert(res2.a instanceof Array, 'merge same key')
console.assert(typeof res2.b === 'string', 'unmerge key will be string')
console.assert(stringify(res2) === 'a=1,3&b=2', 'stringify array value')
// test case end
// load module
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = qs
} else if (typeof window === 'object') {
window.qs = qs
} else {
return qs
}
})()