【发布时间】:2018-07-09 04:58:17
【问题描述】:
当我尝试使用后端的 API 发布元素时,我遇到了莫名其妙的错误。 API 返回代码为 415 的错误,与媒体类型相关:
Failed to load resource: the server responded with a status of 415 ()
我的后端返回此错误:
Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
编辑:Guru 解决方案出错:
Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain' not supported
烦人的是我在请求中添加了这个标头:
Content-Type: application/json
并且正文被正确解析为 JSON 格式。
我用的是Angular 5,我的后端是用Spring开发的。
Angular 客户端代码:
postProject(project: Project) {
const headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:8443/projects', project.body(), {headers: headers})
.map(response => response);
}
body 方法在哪里:
body() {
const object = {
id: this.id,
name: this.name,
'num_execs': this.num_execs
};
return JSON.stringify(object);
}
Spring API 代码:
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addLocation(@RequestBody Project project) {
return new ResponseEntity<>(esProjectService.save(project), HttpStatus.OK);
}
类的RequestMapping是/projects:
@RestController
@RequestMapping("/projects")
public class ProjectResource {
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addLocation(@RequestBody Project project) {
return new ResponseEntity<>(esProjectService.save(project), HttpStatus.OK);
}
... OTHER METHODS...
}
【问题讨论】:
-
您是否尝试将
consumes属性添加到您的spring 方法RequestMapping中?如@RequestMapping(value = "/methodName", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) -
@GuruprasadRao 您的解决方案部分解决了我的错误。现在,输出错误在我编辑的帖子中。
-
能否请您添加有关您的代码的更多详细信息?您的服务器方法以及您在网络控制台中发送客户端请求 + 请求数据的方式..
-
@GuruprasadRao 代码已添加。
-
为什么
value = ""在请求映射中?它将如何映射到/projects?
标签: spring angular api header content-type