当我尝试使用后端的 API 发布元素时,出现莫名其妙的错误。 API 返回代码 415 的错误,与媒体类型相关:
加载资源失败:服务器响应状态为415()
我的后端向我返回此错误:
解决了 Handler 执行引起的异常:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型 'text/plain;charset=UTF-8'
编辑:Guru 解决方案错误:
解决了处理程序执行引起的异常:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“text/plain”
令人烦恼的是,我已将此标头添加到我的请求中:
内容类型: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...
}
我已经经历过这个问题,解决它的一种方法是指定类型 @RequestPart (value = "nameOfResource" and Consumers = {"multipart/form-data"}
不要忘记在 Angular 中指定内容的名称。 我希望它有帮助。
下面是一个例子:
RequestMapping(value = "/add", method = RequestMethod.POST, consumes = {"multipart/form-data"}, produces = "application/json")
public ResponseEntity<?> add(@RequestPart(value = "image", required = true) MultipartFile image,
@RequestPart(value = "team", required = true) @Valid Team team, BindingResult bResult) {
}
在 Angular 5 中,
HttpHeaders
是不可变的。因此,你应该这样使用它
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
});
或
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('X-XSRF-TOKEN', token);
以这种方式设置标题,它应该可以解决您的问题。我放置示例代码只是为了解释如何添加多个标头。如果不需要,请不要添加
'X-XSRF-TOKEN'
。
我认为这个错误来自于你想在发送纯文本/文本时使用应用程序/json。 我解释一下,在您指定的服务中
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
在您的前端代码中发送纯文本/文本
return JSON.stringify(object);
只需删除 JSON.stringify 调用并返回 json 对象即可。
改变
body() {
const object = {
id: this.id,
name: this.name,
'num_execs': this.num_execs
};
return JSON.stringify(object);
}
到
body() {
const object = {
id: this.id,
name: this.name,
'num_execs': this.num_execs
};
return object;
}