How do I POST an array to the server?

Viewed 27

I am trying to post an array of multiple geolocation addresses (generated by Google maps) to my server. The array displays correctly as an array while on the client side, however, the array arrives at the server as a string and not as an array. I am not entirely sure why this happens, also I can't figure out how to convert this string back into an array on the server.

Find below the code of the array while on the client side via the browser:

console.log("Geolocations: " ,selecedAddresses);

This codeabove yields an array of 3 items as illustrated below:

Geolocations: (3) ['Kileleshwa, Nairobi, Kenya', 'Ntinda, Kampala, Uganda', 'Uhuru Highway, Nairobi, Kenya']

When the same array is expanded for better readability:

0: "Kileleshwa, Nairobi, Kenya"
1: "Ntinda, Kampala, Uganda"
2: "Uhuru Highway, Nairobi, Kenya"
length: 3

For me to be able to POST the array to the server, I assign the array value to an HTML input field in a form.

  document.getElementById('locationArray').value = selecedAddresses;

Find below the code to my HTML form where input field resides:

<form action="/advertiser" method="POST" enctype="multipart/form-data">
    <div class="mb-3">
      <input type="text" name="locationArray" value="" hidden/>
    </div> 

    <button type="submit" class="btn btn-secondary"> Add location </button> 
</form>

When the user clicks on the Add location button, the array is submitted to the server. And now for the server side code...

app.route('/Geolocations')
   .post((req, res)=>{ 
       let locationArray = req.body.locationArray;   
       console.log("locationArray: " +locationArray);
   })

The code above yeilds:

locationArray: "Kileleshwa, Nairobi, Kenya, Ntinda, Kampala, Uganda, Uhuru, Highway, Nairobi, Kenya"

Instead of the desired out put:

['Kileleshwa, Nairobi, Kenya', 'Ntinda, Kampala, Uganda', 'Uhuru Highway, Nairobi, Kenya']

Looking forward to your help.

0 Answers
Related