Skip to content
Advertisement

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. 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”. Even when i set specifically the header ‘Content-Type’ to ‘application/json’ it sends like ‘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:

Server response

Here is the method that accept the request in 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.

Advertisement

Answer

In your JavaScript code you need to use „headers“ instead of „header“. See the fetch API documentation: https://developer.mozilla.org/en-US/docs/Web/API/fetch

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement