i have a POST request using springboot, everything works fine when i make tests on postman but when i try it from the browser i get this error,
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.
this is my code.
the Service class
@Transactional(rollbackFor = {SQLException.class})
public ResponseEntity<Message> save(Cursos cursos) {
Optional<Cursos> optionalCursos = cursosRepository.findByTituloCursos(cursos.getTituloCursos());
if (optionalCursos.isPresent()) {
return new ResponseEntity<>(new Message("la entrada ya existe", null), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new Message("ok", false, cursosRepository.saveAndFlush(cursos)), HttpStatus.OK);
}
DTO class
public class CursosDTO {
long id;
@NotNull
String tituloCursos;
@NotNull
String cuerpocursos;
public CursosDTO() {
}
public CursosDTO(long id, String tituloCursos, String cuerpocursos) {
this.id = id;
this.tituloCursos = tituloCursos;
this.cuerpocursos = cuerpocursos;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTituloCursos() {
return tituloCursos;
}
public void setTituloCursos(String tituloCursos) {
this.tituloCursos = tituloCursos;
}
public String getCuerpocursos() {
return cuerpocursos;
}
public void setCuerpocursos(String cuerpocursos) {
this.cuerpocursos = cuerpocursos;
}
}
controller class
@PostMapping("/")
public ResponseEntity<Message> save(@RequestBody CursosDTO cursosDTO) {
Cursos saveCursos = new Cursos(cursosDTO.getTituloCursos(), cursosDTO.getCuerpocursos());
return cursosService.save(saveCursos);
}
and this is my JavaScript code
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
let dataUpd = {
tituloCursos: titulo,
cuerpocursos: contenido
};
console.log(JSON.stringify(dataUpd) " prueba");
fetch(url, {
method: "POST",
BODY: dataUpd,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.catch((error) => console.error("error al subir datos: ", error))
.then((response) => {
console.log("Datos subidos: ", response);
})
})
when i fetch data it brings all the data stored in the db correctly and this is the info that im trying to store
{"tituloCursos":"Stack","cuerpocursos":"<p>Overflown</p>"}
just in case it is relevant im using edge browser and im trying to store info from a rich text editor using tinymce
CodePudding user response:
Probably a very simple typo. You capitalized BODY
in your Post requests js code. It needs to be lowercase: body
See: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
Also, you would need to JSON.stringify your Data so your request options for the Post request would look like this:
method: "POST",
body: JSON.stringify(dataUpd),
headers: {
"Content-Type": "application/json",
},