Angular 9: formData.append('key', null) 实际上附加了 'null' 字符串

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

使用 Typescript/Angular 9:

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

>> 'null'

这是一个 'null' 字符串,而不是 null 值。

我需要以某种方式将 null(或未定义)值附加到 FormData。我能做什么?

你不能,因为如果值不是 USVStringBlob.

,它总是会转换为字符串

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.

但是,如果您删除一个密钥并尝试访问它,默认情况下它将 return 为 null。

let oFormData: FormData = new FormData();

oFormData.append('key1', null);
oFormData.get('key1'); // string 'null'
oFormData.delete('key1');
console.log(oFormData.get('key1')); // null

尝试将 key 设置为 undefined:

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

传递给 data.append 的任何值都将转换为字符串。完成发送空值的唯一方法是发送空字符串。即 formData.append('key', ''); 这将向后端发送一个空值而不对其进行字符串化。