I need to make a request through axios, in which I want to pass as an array an array of this type [1,2,3,4]. I need this data to make a selection query from my backend, my question is: should I use a GET or POST request and what would be the correct way to pass this array?
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    4
            
            
         
    
    
        FeRcHo
        
- 1,119
- 5
- 14
- 27
1 Answers
6
            You  can POST it as json data
let data=[1,2,3,4,5];
let json=JSON.stringify(data);
let post_data={json_data:json}
axios.post('/url',post_data)
- use  JSON.stringifyto convert it to json string
- Use POST method to send data to server
- Use json_decode to convert json back to array on server side
On laravel side you can do like below
$jsonArray = json_decode($response,true);
 
    
    
        sumit
        
- 15,003
- 12
- 69
- 110
- 
                    thanks for answering, apparently everything is fine with my javascript code, but I have problems receiving the array in my laravel driver, apparently this did not work $ jsonArray = json_decode ($ response, true). – FeRcHo Apr 05 '18 at 22:43
- 
                    For best practices, the answer would depend on the purpose of your request, and you shouldn't use get/post interchangeably. Get requests should be idempotent, while post requests are not: https://www.restapitutorial.com/lessons/idempotency.html – Kevin Foster Feb 04 '20 at 01:35
- 
                    I agree, using post is not good, I searched else where and found a decent answer using qs. I will link to that here: https://stackoverflow.com/questions/49944387/how-to-correctly-use-axios-params-with-arrays – Muhammad Mubashirullah Durrani Sep 09 '22 at 11:01
- 
                    I however prefer not installing anything new and have moved to fetch: const storeIds = [1,2,3] const response = await fetch(`url/?${new URLSearchParams ({ storeIds }).toString()`) – Muhammad Mubashirullah Durrani Sep 09 '22 at 11:02