Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 363
Nika Kasradze Avatar asked Jun 10 '20 11:06

Nika Kasradze


People also ask

How do I add null value to FormData?

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.

How do I append in FormData?

append() The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

What is FormData append in angular?

The FormData. append() appends a new value for an existing key, or adds the key if it does not exist. The FormData. delete() method deletes a key/value pair from a FormData object.

What is new FormData ()?

The formData constructor creates and returns a new FormData object. If an HTML form element is provided, it automatically captures its fields. This parameter is optional. Additional data can be added in the FormData object using the formData. append() method.


2 Answers

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.

like image 148
Simone Anthony Avatar answered Sep 17 '22 02:09

Simone Anthony


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
like image 37
Mike S. Avatar answered Sep 17 '22 02:09

Mike S.