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',
},
})
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',
},
})
Share
Improve this question
edited Apr 6, 2022 at 16:39
Eivydas Vickus
asked Apr 6, 2022 at 16:22
Eivydas VickusEivydas Vickus
1896 silver badges14 bronze badges
7
- 1 Could you share the code about how you send a request? – Nick Vu Commented Apr 6, 2022 at 16:35
- @NickVu I added the post request. Also I need to mention that I sending File and data with request – Eivydas Vickus Commented Apr 6, 2022 at 16:40
-
Hmm if your
Content-Type
is different, we can pass an object in the payload, but seemingly you're sending files along with it, so we should format those strings on the server side again. The document here is also telling FormData gets formatted to strings (developer.mozilla/en-US/docs/Web/API/FormData/…) – Nick Vu Commented Apr 6, 2022 at 16:54 - @NickVu Maybe is there another way to send files and data. Without using FormData – Eivydas Vickus Commented Apr 6, 2022 at 16:58
- Hmm seemingly not (maybe I have not done enough research), but if you still want to avoid server data formats, you can have 2 separate calls, one is to upload files, and another is to send data. In this way, you can improve your UX a bit, because you don't block data updates with file upload – Nick Vu Commented Apr 6, 2022 at 17:04
3 Answers
Reset to default 2The value for formData will be converted to a string.
See documentation: https://developer.mozilla/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);
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",
},
});
Before validating the schema in Yup, I used the following method to transform the data. The data es in as a string, but before validation, I convert it:
serviceTags: Yup.array().transform((value, originalValue) => {
if (typeof originalValue === 'string') {
try {
return JSON.parse(originalValue);
} catch (error) {
return []; // Return an empty array if parsing fails
}
}
return value;
});