Home > Net >  FormData everything converting to string even arrays
FormData everything converting to string even arrays

Time:04-07

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

CodePudding user response:

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(',');

CodePudding user response:

 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",
      },
    });
  • Related