The get / delete method of passing array parameters in vue

When interacting between the front and back ends, sometimes it is necessary to pass an array to the backend through get or delete, but such direct transmission to the backend cannot receive data, because the array parameters will be translated during the transfer process. The results are as follows:

Parameters: {name: [1, 2, 3]}
Translation effect: http://aaa.com?name[]=1&name[]=2&name[]=3
Target effect: http://aaa.com?name= 1&name=2&name=3

Solution:
Use the qs plugin to serialize the array parameters

1、qs.stringify({
    
     a: ['b', 'c'] }, {
    
     arrayFormat: 'indices' })
// 输出结果:'a[0]=b&a[1]=c'
2、qs.stringify({
    
     a: ['b', 'c'] }, {
    
     arrayFormat: 'brackets' })
// 输出结果:'a[]=b&a[]=c'
3、qs.stringify({
    
     a: ['b', 'c'] }, {
    
     arrayFormat: 'repeat' })
// 输出结果:'a=b&a=c'
4、qs.stringify({
    
     a: ['b', 'c'] }, {
    
     arrayFormat: 'comma' })
// 输出结果:'a=b,c'

installation

npm install qs

use

//在 axios 请求拦截器里面
import qs from 'qs'
axios.interceptors.request.use(request => {
    
    
  if (request.method === 'delete' || request.method === 'get') {
    
    
   request.paramsSerializer = function(params) {
    
    
     return qs.stringify(params, {
    
     arrayFormat: 'repeat' })
   }
  }
  return request
},(error) =>{
    
    
  return Promise.reject(error);
})

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/115012207