I am trying to save array list of value in flask using form data.This is how i am sending list data from frontend
saveProjectDesign = () => {
var data = new FormData();
data.append('styleCheckedList', this.state.styleCheckedList);
axios.post(this.state.apiUrl+'/api/v1/project/project/projectdesignsave', data, config)
.then((response) => {
console.log("response",response);
if (response.data.status === "success") {
openCustomNotifierSnackbar({ message: response.data.message, duration:3000, notifyType: 'success' });
}
if (response.data.status === "failed") {
openCustomNotifierSnackbar({ message: response.data.message, duration:3000, notifyType: 'error' });
}
})
.catch( (err)=> { console.log(err); });
};
here is the list data in styleCheckedList i am sending from frontend:
0: {styleId: "1"}
1: {styleId: "2"}
2: {styleId: "3"}
This is how tried to retrieve the value ins flask:
styleListChecked = request.form.getlist("styleCheckedList")
But the value is printed in backend like this:
['[object Object],[object Object],[object Object]', '[object Object],[object Object],[object Object]']
what am i doing wrong here?
Here's the issue: FormData
's append
method expects a string, not an array, not an object, but a string. When you passed in that array, JavaScript automatically called .toString()
on it and got that ugly result with a toString
of each element separated by commas. If you want to send an array, you need to append each element individually, as if it were from a POST from an HTML form
for (let element of this.state.styleCheckedList) {
data.append('styleCheckedList[]', element);
}
This treats each element as part of the array styledCheckedList
. You would be done, but there's another problem. Now you're appending objects, not strings to the FormData
, and that will just give you an array of '[object Object]'
on server side. This is where it gets tricky.
It's not possible to send complex JavaScript objects through FormData
. You'll have to either a) encode it in JSON with JSON.stringify()
and decode on the server or b) if you only have the styleId
key in each object, send just element.styleId
.
If you don't care for any of this, JSON.stringify()
the entire object in your current code and JSON.loads()
on the server.
Good luck!