Post object 在 Angular2 中使用 @RequestBody 到 Spring RestContoller
Post object in Angular2 to Spring RestContoller using @RequestBody
客户端和服务器之间的连接工作正常,并且在服务器上调用了正确的函数 addEpic。问题是,只是在服务器上创建了一个新的 Epic 实例,但未使用来自客户端的属性。
@RequestBody 似乎是问题所在。不应该自动将@RequestBody 从json 数据转换为指定的class 吗?
Epic是@Entity的根本问题class?
也可能是客户端错误生成了body。
console.log(body) 显示:
{"epic":{"id":"f97d885a-410f-fa6d-7adc-291e63d35341", "name":"OurName"}}
但是我的 swagger-ui 显示 body 模型 shema:
{"id":"string", "name":"string"}
客户
addEpic(epic:Epic):Observable<any> {
let body = JSON.stringify({epic});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(url + "addEpic", body, options)
.map(this.extractHeader)
.catch(this.handleError);
}
export class Epic {
id: string;
name: string;
}
服务器
@RequestMapping(value="/addEpic", method = RequestMethod.POST)
public ResponseEntity<Void> addEpic(@RequestBody Epic epic) {
// Here it seems that constructor of epic is called and a new instance is created
epicRepository.saveAndFlush(epic);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Epic implements Serializable {
private static final long serialVersionUID = -670305953055479441L;
@Column
private String id;
@Column
private String name
}
您的实体 Epic 有两个属性 'id' 和 'name'。
在 JSON 中:
{"id":"string", "name":"string"}
这正是 Swagger 向您展示的内容。
所以你的客户做错了,你应该在那里创建 JSON 就像
let body = JSON.stringify(epic);
只需删除 'epic' 周围多余的 {}。
客户端和服务器之间的连接工作正常,并且在服务器上调用了正确的函数 addEpic。问题是,只是在服务器上创建了一个新的 Epic 实例,但未使用来自客户端的属性。 @RequestBody 似乎是问题所在。不应该自动将@RequestBody 从json 数据转换为指定的class 吗? Epic是@Entity的根本问题class?
也可能是客户端错误生成了body。 console.log(body) 显示:
{"epic":{"id":"f97d885a-410f-fa6d-7adc-291e63d35341", "name":"OurName"}}
但是我的 swagger-ui 显示 body 模型 shema:
{"id":"string", "name":"string"}
客户
addEpic(epic:Epic):Observable<any> {
let body = JSON.stringify({epic});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(url + "addEpic", body, options)
.map(this.extractHeader)
.catch(this.handleError);
}
export class Epic {
id: string;
name: string;
}
服务器
@RequestMapping(value="/addEpic", method = RequestMethod.POST)
public ResponseEntity<Void> addEpic(@RequestBody Epic epic) {
// Here it seems that constructor of epic is called and a new instance is created
epicRepository.saveAndFlush(epic);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Epic implements Serializable {
private static final long serialVersionUID = -670305953055479441L;
@Column
private String id;
@Column
private String name
}
您的实体 Epic 有两个属性 'id' 和 'name'。 在 JSON 中:
{"id":"string", "name":"string"}
这正是 Swagger 向您展示的内容。
所以你的客户做错了,你应该在那里创建 JSON 就像
let body = JSON.stringify(epic);
只需删除 'epic' 周围多余的 {}。