当我尝试使用后端的 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
编辑:大师解决方案出错:
Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain' not supported
烦人的是我在我的请求中添加了这个标头:
Content-Type: application/json
并且正文被正确解析为 JSON 格式。
我正在使用Angular 5
,我的后端是使用Spring
.
角客户端代码:
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);
}
春天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...
}
我已经经历过这个,解决它的一种方法是指定类型 @RequestPart (value = "nameOfResource" and consumes = {"multipart/form-data"}
不要忘记在 Angular 中指定 Content 的名称。我希望它有所帮助。
下面是一个例子: