Eivydas Vickus
Eivydas Vickus

Reputation: 189

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',
      },
    })

Upvotes: 2

Views: 9191

Answers (3)

Rao Imtinan
Rao Imtinan

Reputation: 60

Before validating the schema in Yup, I used the following method to transform the data. The data comes 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;
});

Upvotes: 0

Gabe
Gabe

Reputation: 2676

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);

Upvotes: 2

Theymiss Developer
Theymiss Developer

Reputation: 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",
      },
    });

Upvotes: 0

Related Questions