Sub topic 6
Sending JSON and Form Data
This chapter assumes you know how to pass an options object to fetch() with method, headers, and body, and how to check response.ok and read a JSON response. This chapter covers what goes inside body and which Content-Type belongs with each kind of body.
What the body can be
The body option accepts several types. Fetch does not convert a plain JavaScript object for you. You choose an encoding, and the server must be able to decode it.
| Body value | Content-Type sent | Who sets the header |
|---|---|---|
| `JSON.stringify(obj)` (a string) | `application/json` | You |
| `URLSearchParams` | `application/x-www-form-urlencoded;charset=UTF-8` | Fetch, automatically |
| `FormData` | `multipart/form-data; boundary=...` | Fetch, automatically |
| `Blob` or `File` | The blob's `type`, if it has one | Fetch, automatically |
| Plain string | `text/plain;charset=UTF-8` | Fetch, unless you override it |
Sending JSON
Most APIs expect JSON. Serialize the object with JSON.stringify and declare the format in the Content-Type header so the server knows how to parse it.
async function createPost(post) {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
createPost({ title: 'Hello', body: 'First post' });Updates and deletes follow the same pattern. PUT replaces a resource and usually carries a full JSON body. DELETE often has no body. Many servers answer a delete with 204 No Content, and calling response.json() on an empty body throws a SyntaxError, so check the status before you parse.
async function updatePost(id, post) {
const response = await fetch(`https://api.example.com/posts/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function deletePost(id) {
const response = await fetch(`https://api.example.com/posts/${id}`, {
method: 'DELETE'
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.status === 204 ? null : response.json();
}Sending form data
Some endpoints expect form encoding rather than JSON. This is common with older backends, OAuth token endpoints, and file uploads.
URL-encoded forms with URLSearchParams
URLSearchParams produces key=value&key2=value2 text and sets its own Content-Type.
const params = new URLSearchParams({
grant_type: 'password',
username: 'ada',
password: 'secret'
});
const response = await fetch('https://api.example.com/oauth/token', {
method: 'POST',
body: params
});
console.log(await response.json());Multipart forms and files with FormData
FormData can hold text fields and files together. You can build it by hand or read it straight from a <form> element.
const form = document.querySelector('#profile-form');
const formData = new FormData(form);
formData.append('source', 'web');
const fileInput = document.querySelector('#avatar');
if (fileInput.files.length > 0) {
formData.append('avatar', fileInput.files[0]);
}
const response = await fetch('https://api.example.com/profile', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);Common mistakes
- Sending a body with GET or HEAD. Fetch throws a
TypeErrorbefore the request goes out. Put the data in the query string instead, for example `/search?${new URLSearchParams({ q: 'fetch' })}`. - Getting the header wrong for JSON. If you leave out
Content-Type, a string body goes out astext/plain, and many frameworks then leave the parsed body empty. - Converting a FormData to JSON by accident.
JSON.stringify(formData)returns"{}". If the server wants JSON, useJSON.stringify(Object.fromEntries(formData)). That only works when there are no files and no repeated keys. - Parsing an empty response. Check for
204before you callresponse.json().
Exercise
A request sends body: formData with headers: { 'Content-Type': 'multipart/form-data' }, and the server reports that it cannot find any fields. What is wrong, and how do you fix it?
Show answer
The manual header has no boundary parameter, so the server cannot tell where each part of the multipart body starts and ends. Remove the Content-Type header so fetch sets multipart/form-data; boundary=... itself.
Exercise
Write a call that sends { done: true } as a PATCH to https://api.example.com/todos/7 and returns the parsed JSON response, throwing on non-2xx statuses.
Show answer
const res = await fetch('https://api.example.com/todos/7', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ done: true }) }); if (!res.ok) throw new Error(HTTP ${res.status}); return res.json();