I have been searching for how to send an array from my react front end to my node/express back end. My first method was this. React:
saveUpdates = (clickEvent) => {
var list = [];
var length = this.props.title.length;
var tally = 0;
for (var i = 0; i < length; i++) {
tally = tally + 1;
var x = document.getElementById(tally).selectedIndex
var y = document.getElementById(tally).options
list.push(y[x].text)
}
const myHeaders = new Headers();
myHeaders.append('Authorization', localStorage.getItem('token'));
const newQuantity = new FormData();
newQuantity.append('quantity', list)
newQuantity.append('userID', localStorage.getItem('customerID'))
fetch('http://localhost:5000/updateQuantity', {
method: 'POST',
headers: myHeaders,
body: newQuantity
})
In this method I am pushing new values to my variable list, initialized as an array. It seems to send to my back end alright. I console.log the value in node and my array looks like this (this particular instance only has two elements):
5,3
The problem with this is that I end up looping through the elements of this array in my node back end for use in a mysql query and it is counting the comma as an element. Is there a way to fix this? Can I re-format this array somehow?
My other option was to set the list array to state and send the state through the header. This is how I did that:
this.setState({totalQuantity: list})
const myHeaders = new Headers();
myHeaders.append('Authorization', localStorage.getItem('token'));
const newQuantity = new FormData();
newQuantity.append('quantity', this.state.totalQuantity)
newQuantity.append('userID', localStorage.getItem('customerID'))
fetch('http://localhost:5000/updateQuantity', {
method: 'POST',
headers: myHeaders,
body: newQuantity
})
This code is very similar to the first method. However here, I set my list array to state (state item totalQuantity is initialized as an array), then send the state through the header. However, when I do this and console.log the result in my node post request, I get a blank line. It seems to be sending nothing. It doesn't even say undefined or null, but rather just prints a blank line (I tested by printing strings above and below). Are either one of these methods acceptable for sending an array from react to node through the header? If so, what adjustments can I make to fix these problems?