繁体   English   中英

使用 Fetch API javascript 将 Content-Type 设置为 application/Json

[英]set Content-Type to application/Json using Fetch API javascript

我正在尝试使用 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 状态错误“不支持的媒体类型”。 即使我专门将 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:("
      })
    })
  });

这是我从服务器得到的响应:

服务器响应

下面是在 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();
    }

我不知道为什么请求以“文本/纯文本”格式发送,我在 postman 中尝试了 Spring 方法,当我以 json 格式发送数据时工作正常。

在您的 JavaScript 代码中,您需要使用“headers”而不是“header”。 请参阅获取 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM