Send Data Objects
Fetch accepts several body types. Choosing the right one determines the content type, the server parser, and whether files can be included.
Body types
- String - sent as text; set the content type yourself.
- URLSearchParams - form-urlencoded key-value data.
- FormData - multipart data, including files.
- Blob - binary data with a MIME type.
- ArrayBuffer / TypedArray - raw bytes.
- ReadableStream - streamed upload where supported.
JSON object
await fetch('/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Draft', tags: ['work'] }),
});
URL-encoded object
const params = new URLSearchParams();
params.set('title', 'Draft');
params.append('tags', 'work');
params.append('tags', 'urgent');
await fetch('/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params,
});
URLSearchParams handles escaping, so ampersands and spaces do not break the payload. The server receives repeated keys as an array or a comma-separated value depending on its parser.
FormData object
const data = new FormData();
data.append('title', 'Draft');
data.append('attachment', file);
await fetch('/api/notes', { method: 'POST', body: data });
Blob and bytes
const blob = new Blob([JSON.stringify(payload)], {
type: 'application/json',
});
await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': blob.type },
body: blob,
});
Choosing a format
- Use JSON when the server owns a JSON API and there are no files.
- Use FormData when files or native form semantics are involved.
- Use URLSearchParams for simple server-rendered form endpoints.
- Use Blob or ArrayBuffer for binary protocols and file imports.
- Use a stream for very large uploads, with feature detection.
Do not mix formats
Setting Content-Type: application/json while sending FormData produces a body the server cannot parse. Let the body type determine the header, or set it to exactly what the server expects.
Back to course overview · Previous: Send JSON Data · Next: Monitoring Progress