admin管理员组

文章数量:1122846

const formData = new FormData();

  const fields = {
    title: bookingTitle,
    image: image,
    phone_number: phone || null
  };

  Object.entries(fields).forEach(([key, value]) => {
    formData.append(key, value);
  });
return formData;
}

I have a function that creates a FormData object, which handles both string and file inputs. One of the fields, phone_number, is optional, so I want to pass null when the user doesn't provide a value.

However, when I append null to the FormData object, it converts it to the string "null" instead of keeping it as a null value.

Since FormData is designed to handle strings and files, is there a way I can correctly represent phone_number as null or exclude it entirely when it's not provided?

const formData = new FormData();

  const fields = {
    title: bookingTitle,
    image: image,
    phone_number: phone || null
  };

  Object.entries(fields).forEach(([key, value]) => {
    formData.append(key, value);
  });
return formData;
}

I have a function that creates a FormData object, which handles both string and file inputs. One of the fields, phone_number, is optional, so I want to pass null when the user doesn't provide a value.

However, when I append null to the FormData object, it converts it to the string "null" instead of keeping it as a null value.

Since FormData is designed to handle strings and files, is there a way I can correctly represent phone_number as null or exclude it entirely when it's not provided?

Share Improve this question asked Nov 22, 2024 at 9:15 CodderCodder 373 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

The issue is because FormData.append() coerces the provided value argument to a string. Per MDN:

The field's value. This can be a string or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.

To work around this you could send an empty string (which, depending on your server-side model binder, may be converted to null).

phone_number: phone || ''

Alternatively you can avoid even sending the phone_number property. You will then need your server-side logic to be more robust to handle the optional property:

const fields = {
  title: bookingTitle,
  image: image
};

if (phone)
  fields.phone_number = phone;

本文标签: javascriptHow can i pass null as a value instead of quotnullquot in formDataStack Overflow