【发布时间】:2022-01-01 06:29:42
【问题描述】:
我正在尝试使用 javascript 中的 Fetch API 将一些表单数据发送到 Spring 应用程序。 我有这个代码来发送表单数据:
document.querySelector('#formPet').addEventListener('submit', event => {
event.preventDefault();
let email= document.querySelector("#email");
fetch('http://localhost:8080/petForm/'+email.value+'/pets', {
method: 'POST',
body: JSON.stringify({
help: "helpme:("
})
})
});
但我收到 415 状态错误“不支持的媒体类型”。即使我将标题“Content-Type”专门设置为“application/json”,它也会像“text/plain”一样发送
fetch('http://localhost:8080/petForm/'+email.value+'/pets', {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
help: "helpme:("
})
})
});
这是我从服务器得到的响应:
这是Spring中接受请求的方法:
@PostMapping("petForm/{id}/pets")
public ResponseEntity<Pet> createPet(@PathVariable("id") String ownerId, @RequestBody Map<String, Object> data){
System.out.println(data);
return ResponseEntity.ok().build();
}
我不知道为什么请求以“文本/纯文本”格式发送,我在邮递员中尝试了 Spring 方法,当我以 json 格式发送数据时工作正常。
【问题讨论】:
标签: javascript java spring spring-boot fetch