【发布时间】:2019-05-06 23:11:12
【问题描述】:
我有一个前端反应应用程序,我在其中向 REST Jax-RS 后端服务器发出请求。
这是正在发送的请求
deletePost = (post) =>{
return deleter(config.restUrl + `posts/${post}`)
}
在这里,我得到了我的后端的标准 URL,带有一个“删除”功能,它只是一种标准化的提取删除方法(也适用于其他实体)。
这是我的 Jax-RS 资源:
@DELETE
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/{id: [0-9]+}")
public Response deletePost(@HeaderParam("authorization") String token, @PathParam("id") Integer id) throws ResourceNotFoundException, AuthenticationException
{
AuthenticationContext authenticationContext = authenticationFacade.authenticateBearerHeader(token);
Post post = postFacade.delete(authenticationContext, id);
return Response.ok(gson.toJson(PostDTO.basic(post))).build();
}
问题是它给了我一个错误,说表单是 HTML/文本:
MessageBodyWriter not found for media type\u003dtext/html, type\u003dclass com.group3.sem3exam.rest.dto.PostDTO, genericType\u003dclass com.group3.sem3exam.rest.dto.PostDTO
由于暗示是PostDTO有错误,所以我去检查了将实体转换为数据传输对象的基本方法,以发送回客户端。
public static PostDTO basic(Post post)
{
return new PostDTO(
post.getId(),
post.getContents(),
post.getCreatedAt(),
null,
ImageDTO.list(post.getImages(), ImageDTO::withoutUser)
);
}
这里它只是调用返回对象新实例的方法。
之前没见过这个错误,不知道怎么处理?
【问题讨论】:
-
尝试将请求中的Accept头设置为application/json。
-
检查是否为您的应用程序注册了消息正文编写器。如果您使用 Jersey 并希望使用 Jackson 作为正文编写器,您可能需要在您的
ApplicationConfig或ResourceConfig类中添加register(JacksonFeature.class);,当然这是在您的依赖项管理器中添加依赖项之后。