Angular 9: formData.append('key', null) actually appends 'null' string
Asked Answered
A

3

20

Using Typescript/Angular 9:

const formData: FormData = new FormData();
formData.append('key', null);
console.log(formData.get('key'));

>> 'null'

this is a 'null' string, as opposed to null value.

I need to somehow append null (or undefined) value to the FormData. What can I do?

Alpenglow answered 10/6, 2020 at 11:57 Comment(1)
you can send like ''Lovell
S
16

You can't, because the value is always converted to a string if it's not a USVString or Blob.

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.

However, if you delete a key and try to access it, it will return null by default.

let oFormData: FormData = new FormData();

oFormData.append('key1', null);
oFormData.get('key1'); // string 'null'
oFormData.delete('key1');
console.log(oFormData.get('key1')); // null
Sunup answered 10/6, 2020 at 12:14 Comment(0)
M
29

Any value passed into data.append will be converted to a string. The only way to accomplish sending a null value is the send an empty string. i.e. formData.append('key', ''); This will send a null value to the backend without stringifying it.

Millford answered 7/6, 2021 at 0:48 Comment(1)
Thanks, server see boolean "null"))Ommatidium
S
16

You can't, because the value is always converted to a string if it's not a USVString or Blob.

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.

However, if you delete a key and try to access it, it will return null by default.

let oFormData: FormData = new FormData();

oFormData.append('key1', null);
oFormData.get('key1'); // string 'null'
oFormData.delete('key1');
console.log(oFormData.get('key1')); // null
Sunup answered 10/6, 2020 at 12:14 Comment(0)
P
-2

Try to set key to undefined:

const formData: FormData = new FormData();
formData.append('key', undefined);
console.log(formData.get('key'));
Picul answered 10/6, 2020 at 12:33 Comment(1)
It returns "undefined" as String. How does that help?Tchad

© 2022 - 2024 — McMap. All rights reserved.