'FormData everything converting to string even arrays
const formData = new FormData()
formData.append('choices', [1, 2, 3])
choices converted to
'1,2,3'
And this is sent to node js which fails zod valdation because it is expecting array. this also same happens with numbers.
axios post request
axios.post('product', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
Solution 1:[1]
const numArray = [1, 2, 3, 4, 5];
const formData = new FormData();
formData.append("data", JSON.stringify(numArray));
Post request
await axios.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
},
});
Solution 2:[2]
The value for formData will be converted to a string.
See documentation: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
The field's value. This can be a USVString or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.
You can convert it back on the server side with:
const choicesArray = choices.split(',').map(Number);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Theymiss Developer |
| Solution 2 |
