Fetch API - Data Objects
Fetch accepts several body types, and each maps to a different content type. Choosing the right object keeps encoding and headers consistent.
Supported body types
string- sent as text.URLSearchParams- form encoding.FormData- multipart form data, including files.BlobandFile- binary data with a file name.ArrayBufferand typed arrays - raw bytes.ReadableStream- streamed upload where supported.
Converting between objects
// Object to FormData
const form = new FormData();
Object.entries({ name: 'Ravi', role: 'editor' })
.forEach(([key, value]) => form.append(key, value));
// FormData to URLSearchParams
const params = new URLSearchParams(form);
// Blob to text
const text = await blob.text();
// Text to Blob
const blob = new Blob([text], { type: 'text/plain' });
// ArrayBuffer to Blob
const binary = new Blob([arrayBuffer], { type: 'application/octet-stream' });
Sending a Blob
const canvas = document.querySelector('canvas');
const blob = await new Promise((resolve) =>
canvas.toBlob(resolve, 'image/png')
);
await fetch('/api/screenshots', {
method: 'POST',
headers: { 'Content-Type': 'image/png' },
body: blob
});
Reading a response as a data object
const response = await fetch('/api/export.csv');
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'report.csv';
link.click();
URL.revokeObjectURL(url);
Always revoke object URLs once the download starts, otherwise the blob stays in memory.
FormData and files
const data = new FormData();
data.append('title', 'Site visit');
data.append('photos', fileInput.files[0]);
data.append('photos', fileInput.files[1]);
await fetch('/api/visits', { method: 'POST', body: data });
Appending the same key more than once sends multiple parts, which servers usually expose as an array.
Compatibility notes
- Typed arrays are sent as their underlying bytes, not as JSON.
- Streams as request bodies are not supported everywhere; feature-detect first.
- A string body with a JSON content type must already be valid JSON.
Back to course overview · Previous: Fetch API - JSON · Next: Fetch API - Custom Request