The problem that axios cannot submit an array

in accordance with this requirement:

localhost/goods?ids[]=1&ids[]=2 

the axios code is as follows:

  var array = [1, 2];
  let json = JSON.stringify(array);
  console.log(json);
  axios.get("http://localhost/goods", json).then(function (res) {
  if (res.code == 200) {
   console.log("ok");
 }
}

the above code seems to be incorrect. How can I use axios to implement this URL request method?


the serialization of the url address and request body parameters seems to be different, and the parameter serialization of url can call qs.stringify using a package called qs.
but axios will automatically serialize the url parameters, so you can directly

axios.get('http://localhost/goods', {
  params: {ids: [1,2]}
})

is the result you want



qsqs.stringifyids[0]=1&ids[1]=2<br><a>easy-mock</a>Content-Type: application/json axios Content-Type: application/x-www-form-urlencodedjquery ajax qs<br>nodereq.on('data')<br>springMVC,jquery axiosqs:1.Content-Type: application/x-www-form-urlencoded;2.URLSearchParams

stringify: function(param){
        var newParam = new URLSearchParams();
        for(var name in param) {
            if(Array.isArray(param[name])){
                for (var val in param[name]) {
                    newParam.append(name+'[]', param[name][val]);
                }
            }else {
                newParam.append(name,param[name]);
            }
        }
        return newParam;
    },

the final result is the same as the request sent by jquery ajax. Of course, a polyfill

needs to be introduced to ensure compatibility.
Menu