我正在尝试使用 react fetch 将 json 对象发送到 spring 控制器。但我收到以下错误。加载资源失败:服务器响应状态为 400(错误请求)
但是get方法可以成功调用。
http://localhost:8080/test/xx/getSprintTasks/ ${this.props.sprintNo}`
react获取:
fetch(`http://localhost:8080/test/xx/addSprintTasks/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: task
})
.then(response => {
console.log(response)
if (response.status >= 200 && response.status < 300) {
alert('Successfully added')
this.setState(prevState => ({
toDoList: [
...prevState.toDoList,
{
id: temp,
note: text
}
]
}))
} else {
alert('Somthing happened wrong')
}
})
.catch(err => err)
我的身体:
const task = JSON.stringify({
sprintNo: "1",
id: "1",
note: "text",
boardName: "todo"
})
我也试过如下:
const task = JSON.stringify({
"sprintNo": "1",
"id": "1",
"note": "text",
"boardName": "todo"
})
我的控制器:
@Controller
@RequestMapping("/xx")
public class TestController {
@RequestMapping(value = "/getSprintTasks/{sprintno}", method = RequestMethod.GET, produces="application/json")
public @ResponseBody Board getSprintTasks(@PathVariable String sprintno) {
Board board = new Board();
board.setSprintNo(sprintno);
board.setUniqueId(56);
board.setDoneList(new Note[]{new Note(3, "deneme"), new Note(4, "hello wrold")});
board.setToDoList(new Note[]{new Note(1, "deneme"), new Note(2, "hello wrold")});
return board;
}
@RequestMapping(value="/addSprintTasks", method = RequestMethod.POST, consumes="application/json")
public void addSprintTasks(@RequestBody Task task) {
System.out.println(task.getBoardName());
System.out.println(task.getId());
System.out.println(task.getNote());
System.out.println(task.getSprintNo());
}
}
任务.java:
public class Task {
private String sprintNo;
private String id;
private String note;
private String boardName;
public Task(String sprintNo, String id, String note, String boardName) {
super();
this.sprintNo = sprintNo;
this.id = id;
this.note = note;
this.boardName = boardName;
}
public String getSprintNo() {
return sprintNo;
}
public void setSprintNo(String sprintNo) {
this.sprintNo = sprintNo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getBoardName() {
return boardName;
}
public void setBoardName(String boardName) {
this.boardName = boardName;
}
}