简体   繁体   中英

415 error when sending POST request to REST API

I'm developping a REST API in JavaEE and a client using this API in ReactJS.

The API works perfectly when I'm using postman, but as soon as I use fetch method in JS to POST JSON information through my client, I'm getting a 415 error: Unsupported Mediatype in my browser's console.

For the API, I'm using Jersey to process requests and Hibernate as ORM. I have genson dependency and as I said, everythig works perfectly fine with Postman. I also checked the result of JSON.stringify() before sending it and it looks fine to me.

Plus, in my server's console, I'm getting this error everytime I try to POST anything :

GRAVE: 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.

I checked and double-checked everything, I'm sending the right headers, the browser identifies the request as 'application/json' content type but it's like my API still doesn't accept it, or receives it as application/octet-stream mediatype.

Here is the method where fetch is done :

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)
}

The method that receives data in the API :

@POST
@Consumes(MediaType.APPLICATION_JSON)
public User createUser(User u){
    return UserController.createUser(u);
}

The controller just create a new instance of User class to run this code in 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 the answer to my problem or has already faced it, please let me know so I can finally move forward with this project.

Thank you in advance,

Arthur

415 is Unsupported Media Type ( https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415 )

try changing

@Consumes(MediaType.APPLICATION_JSON)

to

@Consumes(MediaType.APPLICATION_JSON_VALUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM