Course contentsShow
← JavaScript
Lesson 2284 of 2,72347. Networking PrimitivesFree lesson

Request Body Basics

Sending different body types: strings, FormData, Blob, ArrayBuffer, and URLSearchParams.

Request Body Basics

You'll learn how to send different types of data in the body of HTTP requests using various JavaScript formats.

What is a Request Body?

When you make a POST, PUT, or PATCH request, you often need to send data to the server. This data goes in the request body. Think of it like stuffing an envelope: the envelope (request) can carry different types of contents (body types) depending on what you're mailing.

The Five Main Body Types

The fetch() API accepts several body types:

1. Strings

Plain text or manually-stringified JSON:

fetch('/api/data', {
  method: 'POST',
  body: 'plain text content'
});

2. FormData

Mimics HTML form submissions, great for file uploads:

const form = new FormData();
form.append('username', 'alice');
form.append('file', fileBlob);

fetch('/upload', { method: 'POST', body: form });

3. Blob

Raw binary data, like images or files:

const blob = new Blob(['binary data'], { type: 'image/png' });
fetch('/image', { method: 'POST', body: blob });

4. ArrayBuffer

Low-level binary data for precise control:

const buffer = new Uint8Array([1, 2, 3]).buffer;
fetch('/binary', { method: 'POST', body: buffer });

5. URLSearchParams

Key-value pairs in URL-encoded format:

const params = new URLSearchParams({ key: 'value' });
fetch('/form', { method: 'POST', body: params });

Choosing the Right Type

Use strings for simple data, FormData for forms/files, Blob or ArrayBuffer for binary content, and URLSearchParams for form-style submissions.

Key Takeaway: The fetch() body option accepts strings, FormData, Blob, ArrayBuffer, and URLSearchParams — each suited for different data-sending scenarios.