Sub topic 6
Sending JSON and Form Data
Earlier chapters showed how to read data from a server. This chapter covers the other direction: how to send data to a server. You will learn how fetch encodes each kind of body, which Content-Type it sets for each one, and which mistakes cause a server to receive an empty or garbled payload.
This chapter assumes you already know the method, headers, and body request options from the previous chapter. It also assumes you can check response.ok and read a body with json() or text(), and that you are comfortable with async/await.
What fetch accepts as a body
The body option does not accept just any value. Fetch takes a specific set of types, and each type has its own encoding and its own default Content-Type header. If you understand this table, most upload bugs become easy to find.
| Body value | How it is sent | Default `Content-Type` |
|---|---|---|
| String | UTF-8 text, as is | `text/plain;charset=UTF-8` |
| `URLSearchParams` | `key=value&key2=value2` | `application/x-www-form-urlencoded;charset=UTF-8` |
| `FormData` | Multipart parts separated by a boundary | `multipart/form-data; boundary=...` |
| `Blob` or `File` | Raw bytes | The blob's `type`, or none if it is empty |
| `ArrayBuffer`, typed array, `DataView` | Raw bytes | None |
| `ReadableStream` | Bytes streamed as they are produced | None |
Notice what the table leaves out: JSON has no row. Fetch has no special handling for plain objects. JSON is a string that you produce yourself and label yourself.
Sending JSON
To send JSON you do two things. You turn the object into a string with JSON.stringify, and you tell the server what the string is by setting Content-Type: application/json.
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' })
.then((created) => console.log('Created post', created.id))
.catch((err) => console.error(err.message));Both steps are required. Each one fails in its own way when you leave it out.
Mistake 1: passing the object directly
// Wrong: the object is converted with String(), not JSON.stringify()
await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: { title: 'Hello' }
});Fetch does not throw here. Any value that is not one of the supported body types gets converted to a string, so the server receives the literal text [object Object]. A JSON parser on the server then fails, and you usually see a 400 response with a vague "Unexpected token o" message.
Mistake 2: forgetting the Content-Type header
If you stringify the object but skip the header, the body is valid JSON labelled text/plain;charset=UTF-8. Many server frameworks choose a parser based on Content-Type. Express's express.json() middleware, for example, only parses requests labelled application/json. Other requests pass through untouched, and the handler sees req.body as {} or undefined. The request succeeds and the data disappears without any error, which makes this mistake harder to spot than the first.
What JSON.stringify drops or changes
JSON.stringify is lossy, so check what it produces for your data:
- Properties whose value is
undefined, a function, or a symbol are dropped from objects. Inside arrays they becomenull. Dateobjects become ISO 8601 strings, such as"2026-11-24T10:08:10.731Z". The server receives a string, not a date.MapandSetbecome{}.NaNandInfinitybecomenull.BigIntvalues throw aTypeError, and so do circular references. This happens before the request is sent.
const payload = {
name: 'Ada',
nickname: undefined,
createdAt: new Date(Date.UTC(2026, 10, 24)),
tags: new Set(['math', 'engines'])
};
console.log(JSON.stringify(payload));
// {"name":"Ada","createdAt":"2026-11-24T00:00:00.000Z","tags":{}}
const fixed = { ...payload, tags: [...payload.tags] };
console.log(JSON.stringify(fixed));
// {"name":"Ada","createdAt":"2026-11-24T00:00:00.000Z","tags":["math","engines"]}To send "clear this field", use null explicitly. Because undefined is dropped, { nickname: undefined } and {} look the same to the server.
PUT, PATCH, and DELETE
The JSON pattern works the same for every method that carries a body. The difference between the methods is what they mean. PUT replaces a whole resource. PATCH changes only the fields you send. DELETE usually has no body.
const base = 'https://api.example.com/posts';
async function send(url, method, data) {
const init = { method };
if (data !== undefined) {
init.headers = { 'Content-Type': 'application/json' };
init.body = JSON.stringify(data);
}
const response = await fetch(url, init);
if (!response.ok) throw new Error(`${method} ${url}: HTTP ${response.status}`);
// 204 No Content has an empty body; calling json() on it would throw
return response.status === 204 ? null : response.json();
}
await send(`${base}/42`, 'PUT', { title: 'Replaced', body: 'All fields sent' });
await send(`${base}/42`, 'PATCH', { title: 'Only the title changes' });
await send(`${base}/42`, 'DELETE');Two edge cases come up often:
- Bodies on GET or HEAD. Fetch throws a
TypeErrorsynchronously when you pass abodywithGETorHEAD. To send parameters with a GET request, put them in the query string, as shown later in this chapter. - Empty success responses.
DELETEandPATCHoften return204 No Content.response.json()rejects with aSyntaxErroron an empty body, so check the status, or read the body withtext()and parse it only when it is not empty.
Sending form data with FormData
FormData is a list of name and value pairs that is encoded as multipart/form-data. This is the format a browser uses when an HTML form with enctype="multipart/form-data" is submitted. It is the standard way to upload files, because each part can carry binary data along with its own filename and type.
Here is a form with a file input:
<form id="profile">
<input name="displayName" value="Ada">
<input name="interests" type="checkbox" value="math" checked>
<input name="interests" type="checkbox" value="engines" checked>
<input name="avatar" type="file" accept="image/*">
<button>Save</button>
</form>This script submits the form with fetch instead of reloading the page:
const form = document.querySelector('#profile');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
formData.append('source', 'web');
const response = await fetch('https://api.example.com/profile', {
method: 'POST',
body: formData
});
if (!response.ok) {
console.error(`Upload failed: HTTP ${response.status}`);
return;
}
console.log('Saved', await response.json());
});new FormData(form) collects every named, enabled control in the form. Checked checkboxes and selected files are included, and unchecked boxes are left out. You can also build a FormData by hand and attach in-memory data as a file:
const formData = new FormData();
formData.append('title', 'Quarterly report');
const csv = new Blob(['region,total\nnorth,120\nsouth,98\n'], { type: 'text/csv' });
formData.append('file', csv, 'report.csv'); // third argument sets the filename
await fetch('https://api.example.com/uploads', { method: 'POST', body: formData });Do not set Content-Type for FormData
This is the most common FormData bug. A multipart body is split into parts by a random boundary string, and the server needs that string to find where each part starts and ends. Fetch generates the boundary and writes it into the header, for example multipart/form-data; boundary=----WebKitFormBoundaryX7f....
If you set 'Content-Type': 'multipart/form-data' yourself, your value replaces the generated one and the boundary is lost. The server then cannot split the body, and it usually reports that no fields or files were received.
append() versus set(), and turning FormData into JSON
append(name, value) adds a new entry even when the name already exists. set(name, value) replaces every existing entry with that name. Repeated names are normal in forms. The two interests checkboxes above produce two entries.
That causes trouble when you convert form data to JSON for an API that only accepts JSON:
const formData = new FormData();
formData.append('displayName', 'Ada');
formData.append('interests', 'math');
formData.append('interests', 'engines');
console.log(Object.fromEntries(formData));
// { displayName: 'Ada', interests: 'engines' } <- 'math' is lost
const payload = {
displayName: formData.get('displayName'),
interests: formData.getAll('interests')
};
console.log(JSON.stringify(payload));
// {"displayName":"Ada","interests":["math","engines"]}Object.fromEntries keeps only the last value for each name. Use getAll() for any field that can repeat. Keep in mind that File values cannot be put into JSON. Once a form contains a file, send the FormData itself.
URL-encoded data with URLSearchParams
Some endpoints expect application/x-www-form-urlencoded, the default encoding for a plain HTML form. OAuth token endpoints and many older backends work this way. URLSearchParams produces this format and escapes special characters for you:
const params = new URLSearchParams({
grant_type: 'client_credentials',
scope: 'read write'
});
console.log(params.toString()); // grant_type=client_credentials&scope=read+write
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
body: params
});The same object builds query strings for GET requests, which is the correct place for GET parameters:
const url = new URL('https://api.example.com/search');
url.searchParams.set('q', 'fetch & streams');
url.searchParams.set('page', '2');
const response = await fetch(url);
console.log(url.href); // https://api.example.com/search?q=fetch+%26+streams&page=2Do not build query strings by joining text together. In ` ?q=${term} , an & or # inside term` breaks the URL.
Choosing an encoding
The format the server accepts always decides the question. Check the API documentation, or a working request in another tool, before you pick one.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Server receives `[object Object]` | Object passed as `body` | Wrap it in `JSON.stringify()` |
| Server body is `{}` or empty | JSON sent without `Content-Type: application/json` | Add the header |
| "Missing boundary" or no files received | `Content-Type` set manually with `FormData` | Remove the header |
| `TypeError` before the request is sent | Body on a GET or HEAD request, or a BigInt or circular value | Use the query string, or convert the value |
| `SyntaxError` after a successful DELETE | `json()` called on a 204 response | Check the status before parsing |
| Only one checkbox value arrives | `Object.fromEntries(formData)` | Use `getAll()` |
Exercise
A teammate's upload code sends a FormData object containing a file, with headers set to { 'Content-Type': 'multipart/form-data' }. The server answers 400 with "Multipart: Boundary not found". Explain the cause and give the fix.
Show answer
The multipart body is split into parts by a boundary string that fetch generates and writes into the Content-Type header, for example multipart/form-data; boundary=----abc123. Setting the header manually replaces that value and removes the boundary, so the server cannot find where each part begins. The fix is to delete the Content-Type header and let fetch set it automatically from the FormData body.
Exercise
What does the server receive as the request body here, and what Content-Type does fetch send? fetch(url, { method: 'POST', body: JSON.stringify({ id: 7, note: undefined, at: new Date(0) }) })
Show answer
The body is the string {"id":7,"at":"1970-01-01T00:00:00.000Z"}. The note property is dropped because its value is undefined, and the Date becomes an ISO string. Because the body is a string and no header was set, fetch sends Content-Type: text/plain;charset=UTF-8, so a server that picks its parser by content type may not parse it as JSON. Add headers: { 'Content-Type': 'application/json' }.
Exercise
Write a function updateTags(id, form) that reads every value of the repeated "tags" field from an HTML form element and sends them as a JSON PATCH request to https://api.example.com/items/{id}. It should return null for a 204 response, return the parsed JSON otherwise, and throw on a non-OK status.
Show answer
async function updateTags(id, form) { const tags = new FormData(form).getAll('tags'); const response = await fetch(https://api.example.com/items/${id}, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tags }) }); if (!response.ok) throw new Error(HTTP ${response.status}); return response.status === 204 ? null : response.json(); } The key points are getAll() to keep every tag, JSON.stringify with an explicit Content-Type, and the 204 check before calling json().