我已经在我的React应用中配置了POST请求,如下所示:
await fetch('http://localhost:8080/api/room', { credentials: 'include' }, {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
'body': JSON.stringify(somedata),
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log('Error', error);
});
在我的spring-boot应用程序中,我有一个控制器:
@RequestMapping(value = "/room", produces = "application/json", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<Room> createRoom(@Valid @RequestBody Room room) throws URISyntaxException {
Room result = roomService.saveOrUpdate(room);
return ResponseEntity.created(new URI("/api/room/" + result.getRoomClientId()))
.body(result);
}
在我的浏览器控制台中,我得到以下响应:
Response {type: "cors", url: "http://localhost:8080/api/room",
redirected: false, status: 400, ok: false, …}
在我的spring-boot应用程序控制台中,出现此错误:
2019-04-08 16:31:42.742 WARN 86177 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<com.sbpoc.app.db.entity.Room> com.sbpoc.app.db.controller.RoomController.createRoom(com.sbpoc.app.db.entity.Room) throws java.net.URISyntaxException]
错误说,请求正文丢失了?
更新
import uniqid from 'uniqid';
const someData = {
roomNumber: uniqid(),
}
房间实体:
@Entity
public class Room implements Serializable {
private static final long serialVersionUID = 3433823138738252949L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String roomNumber;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
}
答案 0 :(得分:0)
我需要将凭据选项包含在一个对象中,例如:
zonetype1
在springboot应用程序中,我还使用了@PostMapping:
fetch('http://localhost:8080/api/room',
{
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify(data)
}
)
.then(res => console.log(res));