[英]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. 我正在JavaEE中开发REST API,并在ReactJS中使用该API开发客户端。
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. 当我使用邮递员时,该API可以完美运行,但是一旦我在JS中使用fetch方法通过客户端发布JSON信息,就会收到415错误:浏览器控制台中的媒体类型不受支持。
For the API, I'm using Jersey to process requests and Hibernate as ORM. 对于API,我正在使用Jersey处理请求并将Hibernate作为ORM。 I have genson dependency and as I said, everythig works perfectly fine with Postman.
我有genson依赖性,正如我所说,everythig与Postman可以完美地工作。 I also checked the result of JSON.stringify() before sending it and it looks fine to me.
在发送前,我还检查了JSON.stringify()的结果,对我来说看起来不错。
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. 我检查并仔细检查了所有内容,正在发送正确的标头,浏览器将请求标识为“ application / json”内容类型,但这就像我的API仍不接受它,或者将其作为应用程序/八位字节流接收媒体类型。
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 : 在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 : 控制器只是创建User类的新实例以在User模型类中运行以下代码:
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 ) 415是不受支持的媒体类型( https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415 )
try changing 尝试改变
@Consumes(MediaType.APPLICATION_JSON)
to 至
@Consumes(MediaType.APPLICATION_JSON_VALUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.