Home > Software design >  set Content-Type to application/Json using Fetch API javascript
set Content-Type to application/Json using Fetch API javascript

Time:11-23

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.

CodePudding user response:

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

CodePudding user response:

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" 
  • Related