我正在嘗試使用 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 格式發送資料時作業正常。
uj5u.com熱心網友回復:
在您的 JavaScript 代碼中,您需要使用“headers”而不是“header”。查看獲取 API 檔案:https : //developer.mozilla.org/en-US/docs/Web/API/fetch
uj5u.com熱心網友回復:
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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363546.html
標籤:javascript 爪哇 春天 弹簧靴 拿来
