You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular的PUT请求为何发送空请求体?

问题原因与解决方案

问题根源

你用Object.defineProperty创建的属性默认是不可枚举的,而Angular的HttpClient在序列化请求体时,只会遍历对象的可枚举属性并转换为JSON。这就导致后端接收到的请求体为空。

解决方案

方案1:定义属性时显式设置enumerable: true

修改Object.defineProperty的配置,给每个属性加上enumerable: true:

let newData = {};

Object.defineProperty(newData, 'newTitle', {
  value: this.taskForm.value.title,
  enumerable: true // 新增配置
});

Object.defineProperty(newData, 'newDescription', {
  value: this.taskForm.value.description,
  enumerable: true // 新增配置
});

Object.defineProperty(newData, 'newSubtasks', {
  value: this.taskForm.value.subtasks,
  enumerable: true // 新增配置
});

this.http.editTask(this.taskId, newData).subscribe();

方案2:直接使用对象字面量/属性赋值(更简洁)

没必要用Object.defineProperty的话,直接创建对象更简单,这种方式下属性默认就是可枚举的:

// 方式A:对象字面量
let newData = {
  newTitle: this.taskForm.value.title,
  newDescription: this.taskForm.value.description,
  newSubtasks: this.taskForm.value.subtasks
};

// 方式B:直接赋值
let newData = {};
newData.newTitle = this.taskForm.value.title;
newData.newDescription = this.taskForm.value.description;
newData.newSubtasks = this.taskForm.value.subtasks;

this.http.editTask(this.taskId, newData).subscribe();

方案3:用Object.defineProperties批量设置属性

如果必须使用Object.defineProperty系列方法,可以一次性定义多个属性:

let newData = {};
Object.defineProperties(newData, {
  newTitle: {
    value: this.taskForm.value.title,
    enumerable: true
  },
  newDescription: {
    value: this.taskForm.value.description,
    enumerable: true
  },
  newSubtasks: {
    value: this.taskForm.value.subtasks,
    enumerable: true
  }
});

this.http.editTask(this.taskId, newData).subscribe();

内容的提问来源于stack exchange,提问作者Altaïr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:46:08