I am currently working on developing a REST API in JavaEE and a client in ReactJS that interacts with this API.
When I use Postman to test the API, everything works perfectly fine. However, when I try to make POST requests using the fetch method in JavaScript from my client, I encounter a 415 error:
"Unsupported MediaType" is displayed in my browser's console.
For the API implementation, Jersey is used for request processing and Hibernate as ORM. I have included the genson dependency and verified that all works well with Postman.
Before sending any data, I also checked the result of JSON.stringify()
and it appears correct.
In addition, every time I attempt to perform a POST request, I notice this error message in my server's console:
"A message body reader for Java class model.User, and Java type class model.User, and MIME media type application/octet-stream was not found."
Despite confirming that the correct headers are being sent and the content type is identified as 'application/json' by the browser, it seems like the API still does not accept or recognizes it as application/octet-stream mediatype.
Below is the code snippet where the fetch request is made:
signIn(){
console.log(JSON.stringify(this.state));
fetch('http://localhost:8080/P52/users', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
return res.json();
}).catch(err=>err)
}
This is the method in the API that handles incoming data:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public User createUser(User u){
return UserController.createUser(u);
}
The controller simply creates a new instance of the User class to execute the code within the User model class :
public User(User u){
this.id = u.getId();
this.pseudo = u.getPseudo();
this.firstname = u.getFirstname();
this.lastname = u.getLastname();
Session session = (Session)HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(this);
session.getTransaction().commit();
session.close();
}
If anyone has encountered this issue before or knows how to solve it, please share your insights so I can progress with this project. Your help would be greatly appreciated!