Issue
Note: Using Flask & Reactjs
I'm currently struggling with a bug where I'm posting a 3-d array from my frontend to my backend and I'm trying to retrieve it using request.form.get('array',type=list), but it ends up being recieved as a 1d array.
Frontend:
let data = new FormData();
this.array = [[[1,4],[2,4]],[[3,1],[2,4]],[[7,4],[1,1]]]
data.append("array", this.array);
return axios
.post(this.url+`/post_arr`, data, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {console.log('hi')
})
}) }
backend:
@app.route('/post_arr',methods=['POST'])
def test():
print(request.form.get('array',type=list))
>['1','4','2','4','3','1','2','4','7','4','1','1']
Rather than retrieving the array as a 3-d array, it retrieves it as a flattened 1d array, which is not ideal. Is there a way to solve this?
Solution
When you append a multidimensional array to the javascript formData
object, it will get automatically transformed into a flattened string.
What you need in javascript is:
let data = new FormData();
this.array = [[[1,4],[2,4]],[[3,1],[2,4]],[[7,4],[1,1]]];
data.append("array", JSON.stringify(array));
Then in flask:
The getlist
method is what you're looking for.
Try the following:
array = request.form.getlist('array')
if it returns in a string like this ['[[[1,4],[2,4]],[[3,1],[2,4]],[[7,4],[1,1]]]']
, simply get the list using the first index: array[0]
should return
[[[1,4],[2,4]],[[3,1],[2,4]],[[7,4],[1,1]]]
Answered By - Parzival
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.