Multiple fields with same key in query params (axios request)?

前端 未结 5 1978
甜味超标
甜味超标 2020-12-05 04:27

So the backend (not under my control) requires a query string like this:

http://example.com/?foo=5&foo=2&foo=11

But axios

5条回答
  •  青春惊慌失措
    2020-12-05 04:58

    If one uses the ready URLSearchParams the handling of multiple parameter values with the same name works with axios as well ... I guess the support for IE came in 2017 ... Works on Safari too, although the links claims that it might not ..

    function getUrlParams(){
            // handles multiple param values with the same name
            var url_params = new URLSearchParams(); 
    
            if( window.location.toString().indexOf("?") != -1) {
               window.location.search.split('?')[1].split('#')[0]
                  .replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
                  var attr = decodeURIComponent(key)
                  var val = decodeURIComponent(value)
                  url_params.append(attr,val);
               });
            } else {
               // create a default set of params - you might not need this one ...
               url_params = { some_param:"some_value" };
            }
            return url_params ;
         }
    
    
         function getBackEndData(url_params, back_end_url){
               // the replace is just a fancy way of converting front-end to back-end call
               return axios.get( back_end_url , { params: url_params } )
               .then(response => {
                  return response.data ;
               })
               .catch(function(error) {
                  return error.response ; 
                  console.log(error.response.data);
               })
         }
    

提交回复
热议问题