文章参考
不推荐使用 axios 的qs 库了,建议参考
URLSearchParams解析url地址栏参数
问题描述
- 工作中,起初和后台约定使用post传递数据,传递是一个JOSN
- 结果后台搞不定,后面又约定将请求改为get
- 这样就要求我传递参数的方式发生改变
解决办法
- 遍历JSON对象,改为 get 请求传参方式
- 使用第三方的库 ‘qs’
案例
const qs = require('qs')
const url = 'method=query_sql_dataset_data&projectId=85&appToken=7d22e38e-5717-11e7-907b-a6006ad3dba0';
// 转为对象
console.log(qs.parse(url));
/**
{
method: 'query_sql_dataset_data',
projectId: '85',
appToken: '7d22e38e-5717-11e7-907b-a6006ad3dba0'
}
*/
const a = {name:'hehe',age:10};
// 转为url参数形式
// name=hehe&age=10
console.log(qs.stringify(a))
qs.parse
将 get 参数转为JSON对象qs.stringify
将 JSON对象 转为 get 的参数方式