【问题标题】:set Content-Type to application/Json using Fetch API javascript使用 Fetch API javascript 将 Content-Type 设置为 application/Json
【发布时间】: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


    【解决方案1】:
    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" 
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    在您的 JavaScript 代码中,您需要使用“headers”而不是“header”。请参阅 fetch API 文档:https://developer.mozilla.org/en-US/docs/Web/API/fetch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多