编程知识 cdmana.com

axios 之传递数组参数 探究(示例篇)

get 方式,对params做处理

  • 通过 paramsSerializer 指定序列化配置
axios.get(`http://localhost:8080/array`, 
  {
    
    params: {
    
      "ids": ["1", "2"]
    },
    paramsSerializer: function (params) {
    
      return Qs.stringify(params, {
     arrayFormat: 'repeat' })
    }
  }
);

效果:http://localhost:8080/array?ids=1&ids=2

post 方式,对data做处理

  • 通过 transformRequest 指定序列化配置
axios.post(`http://localhost:8080/bean/list2`, 
	{
    
        "beans": [
            {
     "id": "1", "name": "1" },
            {
     "id": "2", "name": "2" }
        ],
    }, 
    {
    
        transformRequest: [function (data, headers) {
    
            return Qs.stringify(data, {
     arrayFormat: 'indices', allowDots: true });
        }]
    }
);
  • 直接对数据序列化
axios.post(`http://localhost:8080/bean/list2`,
    Qs.stringify({
    
        "beans": [
            {
     "id": "1", "name": "1" },
            {
     "id": "2", "name": "2" }
        ],
    }, {
    
        arrayFormat: 'indices',
        allowDots: true
    })
);

效果:POST http://localhost:8080/bean/list2
Content-Type: application/x-www-form-urlencoded
form表单的数据为:
beans[0].id: 1
beans[0].name: 1
beans[1].id: 2
beans[1].name: 2

如何测试的?浏览器Console即可

//指定如下命令,引入包,执行上诉代码
var script = document.createElement('script');
script.src = "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
var script = document.createElement('script');
script.src = "https://cdnjs.cloudflare.com/ajax/libs/qs/6.10.1/qs.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

版权声明
本文为[markix]所创,转载请带上原文链接,感谢
https://markix.blog.csdn.net/article/details/121584965

Scroll to Top