[英]set Content-Type to application/Json using Fetch API javascript
I am trying to send some form data to a spring application using Fetch API in javascript.我正在尝试使用 javascript 中的 Fetch API 将一些表单数据发送到 spring 应用程序。 I have this code to send the form data:
我有这个代码来发送表单数据:
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:("
})
})
});
but i get a 415 status error "Unsupported Media Type".但我收到 415 状态错误“不支持的媒体类型”。 Even when i set specifically the header 'Content-Type' to 'application/json' it sends like 'text/plain'
即使我专门将 header '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:("
})
})
});
this is the response that i get from the server:这是我从服务器得到的响应:
Here is the method that accept the request in Spring:下面是在 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();
}
i don´t know why the request is send in 'text/plain' format, i try the Spring method in postman and work´s fine when i send the data in json format.我不知道为什么请求以“文本/纯文本”格式发送,我在 postman 中尝试了 Spring 方法,当我以 json 格式发送数据时工作正常。
In your JavaScript code you need to use „headers“ instead of „header“.在您的 JavaScript 代码中,您需要使用“headers”而不是“header”。 See the fetch API documentation: https://developer.mozilla.org/en-US/docs/Web/API/fetch
请参阅获取 API 文档: https://developer.mozilla.org/en-US/docs/Web/API/fetch
step 1 : add @CrossOrigin after @PostMapping(value = "petForm/{id}/pets")
like :
@PostMapping(value = "petForm/{id}/pets")
@CrossOrigin
public ResponseEntity<String> createPet(@PathVariable("id") String ownerId, @RequestBody Map<String, Object> data){
System.out.println(data);
return ResponseEntity.ok().build();
}
step 2 : add double quotes to help word
it is not json fromat :====> help: "helpme"
Correct :
it is not json fromat :====> "help": "helpme"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.