Why do you need to use JSON.stringify() in the body field of a fetch function

Here is the skeleton to call the fetch() function in JavaScript:

javascript
let response = await fetch(url, {
    
    method:  'POST',
    headers: {'Content-Type': 'application/json'},
    body:    JSON.stringify({name: 'Elon', year: 1971})
    
});

Per the documentation:

Both requests and responses may contain body data. A body is an instance of any of the following types:

  • ArrayBuffer
  • ArrayBufferView (Uint8Array and friends)
  • Blob/File
  • string
  • URLSearchParams
  • FormData

As you can see, you can't use an object in the body field, that's the reason why you should use JSON.stringify() instead of an object like in the headers field.

If you don't want to stringify your object, you could aso use the following request:

javascript
let response = await fetch(url, {
    
    method:  'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body:    'name=Elon&year=1971'
    
});

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.