我正在尝试使用react fetch将json对象发送到spring控制器。但是我收到以下错误。 无法加载资源:服务器的响应状态为400(错误请求)
但是get方法可以成功调用。
http://localhost:8080/test/xx/getSprintTasks/ $ {this.props.sprintNo}`
反应获取:
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());
}
}
Task.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;
}
}
答案 0 :(得分:2)
您的Task.java
不是POJO。
提供默认的构造函数实现,然后重试。
有时您可能需要清理项目才能使更改生效。
答案 1 :(得分:0)
您对react的发布网址为http://localhost:8080/test/xx/addSprintTasks/,但在spring控制器上的发布网址为http://localhost:8080/test/xx/addSprintTasks
删除javascript上的最后一个斜杠,或将其添加到java上@RequestMapping批注的值上。