Sub topic 5
Configuring Requests: Methods, Headers, and Bodies
So far every request in this tutorial has been a plain GET: you passed a URL to fetch() and read what came back. Real applications also create, update, and delete data, send credentials in headers, and upload files. All of that goes through the second argument to fetch(), an options object usually called init.
This chapter assumes you know how to call fetch(), check response.ok, and read a body with response.json() or response.text(), all covered in earlier chapters. You should also know HTTP methods and status codes and be comfortable with async/await. The next chapter covers JSON and form encoding in detail, and a later chapter covers the Headers interface. This chapter gives the overall model they both build on.
The Shape of a fetch Call
fetch() takes two arguments:
fetch(resource, init);resourceis a URL string, aURLobject, or aRequestobject.initis an optional plain object. Each property configures one part of the request.
The three properties you will set most often are method, headers, and body. The others (signal, mode, credentials, cache, redirect, and a few more) have their own sections later in this chapter or in later chapters.
Choosing the Method
The method property sets the HTTP verb. When you leave it out, it defaults to 'GET'.
| Method | Typical use | Has a request body? |
|---|---|---|
| GET | Read a resource | No, and fetch forbids one |
| HEAD | Read only the headers | No, and fetch forbids one |
| POST | Create a resource or trigger an action | Usually |
| PUT | Replace a resource entirely | Usually |
| PATCH | Change part of a resource | Usually |
| DELETE | Remove a resource | Rarely |
| OPTIONS | Ask what the server allows | Rarely |
Here are a full replacement with PUT and a partial update with PATCH:
async function replaceUser(id, user) {
const response = await fetch(`https://api.example.com/users/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function renameUser(id, name) {
const response = await fetch(`https://api.example.com/users/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}Gotcha: Only Some Method Names Are Uppercased
The Fetch standard normalizes DELETE, GET, HEAD, OPTIONS, POST, and PUT to uppercase, so method: 'post' works. PATCH is not on that list. If you write method: 'patch', the browser sends the lowercase string patch on the wire. HTTP method names are case-sensitive, so many servers answer with 405 Method Not Allowed or 400 Bad Request. Write every method in uppercase and the problem never comes up.
Gotcha: GET and HEAD Cannot Have a Body
If you pass a body with a GET or HEAD request, fetch() does not send anything. It rejects right away with a TypeError:
fetch('https://api.example.com/search', {
method: 'GET',
body: JSON.stringify({ q: 'fetch' })
}).catch((err) => console.log(err.name)); // 'TypeError'Send GET parameters in the query string instead. URLSearchParams handles the encoding:
async function search(query, page) {
const url = new URL('https://api.example.com/search');
url.searchParams.set('q', query);
url.searchParams.set('page', String(page));
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
search('fetch & streams', 2); // ...?q=fetch+%26+streams&page=2Building the URL with URL and searchParams escapes characters like &, =, and spaces. Pasting raw values into a template literal does not.
DELETE and Empty Responses
A successful DELETE often returns 204 No Content, which has no body. Calling response.json() on an empty body throws a SyntaxError, so check the status before you parse:
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();
}Setting Headers
The headers property accepts any of three forms:
// 1. A plain object
const asObject = { Accept: 'application/json', 'X-Request-Id': 'abc123' };
// 2. An array of [name, value] pairs, which allows repeated names
const asPairs = [
['Accept', 'application/json'],
['X-Request-Id', 'abc123']
];
// 3. A Headers instance (covered in its own chapter)
const asHeaders = new Headers(asObject);
async function demo() {
for (const headers of [asObject, asPairs, asHeaders]) {
const response = await fetch('https://api.example.com/me', { headers });
console.log(response.status);
}
}A plain object is the most common form and works for nearly every request. Header names are case-insensitive, so accept and Accept mean the same header. Keep in mind that a plain object can hold both 'content-type' and 'Content-Type' as separate keys. The browser merges them into one header with both values joined by a comma, and that is almost never what you meant. Pick one spelling and stick to it.
The headers you will set most often:
| Header | Purpose |
|---|---|
| `Content-Type` | Format of the body you are sending |
| `Accept` | Formats you are willing to receive |
| `Authorization` | Credentials, such as `Bearer <token>` |
| Custom `X-...` headers | Application-specific data such as request IDs |
Forbidden Headers
Browsers control some headers themselves and silently drop any value you set for them. They include Host, Content-Length, Cookie, Origin, Referer, Connection, and any name starting with Proxy- or Sec-. No error is thrown, and the header simply never shows up in the network panel. If a header seems to vanish, check whether it is on this list. Cookies are controlled through the credentials option, covered in the CORS chapter.
Server runtimes such as Node.js do not apply all of these browser restrictions, so the same code can behave differently there.
Choosing a Body Type
The body property accepts several types. The type you pass decides how the bytes are encoded and, unless you override it, which Content-Type the browser sets.
| Body type | Default `Content-Type` | Typical use |
|---|---|---|
| `string` | `text/plain;charset=UTF-8` | JSON text (override the type), plain text |
| `URLSearchParams` | `application/x-www-form-urlencoded;charset=UTF-8` | Classic HTML form posts |
| `FormData` | `multipart/form-data; boundary=...` | Forms with file uploads |
| `Blob` / `File` | The blob's own `type`, if set | Uploading a file as raw bytes |
| `ArrayBuffer`, typed array, `DataView` | None | Binary protocols |
| `ReadableStream` | None | Streaming uploads (limited support) |
Three of these lead to most bugs.
Mistake 1: Passing an Object Directly
fetch() does not serialize objects for you. Any value that is not one of the types above is converted to a string, and a plain object turns into "[object Object]":
// Wrong: the server receives the text "[object Object]" as text/plain
fetch('https://api.example.com/posts', {
method: 'POST',
body: { title: 'Hello' }
});
// Right: serialize the object and label the format
fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello' })
});Mistake 2: Forgetting Content-Type for JSON
JSON.stringify() returns a string, and a string body defaults to text/plain. Many server frameworks only parse the body as JSON when the header says application/json, so without the header the server sees an empty or undefined body. Set the header every time you send JSON.
Mistake 3: Setting Content-Type for FormData
With FormData, the browser builds a multipart body and creates a random boundary string that separates the parts. That boundary goes in the Content-Type header. If you set Content-Type: multipart/form-data yourself, the boundary is missing and the server cannot split the parts. Leave the header unset:
async function uploadAvatar(file) {
const form = new FormData();
form.append('avatar', file);
form.append('caption', 'Profile picture');
const response = await fetch('https://api.example.com/avatar', {
method: 'POST',
body: form // no Content-Type header: the browser adds it with the boundary
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}The next chapter goes into JSON, URL-encoded, and multipart encoding in more detail.
Request Bodies Are Single-Use Too
A stream body (ReadableStream) can only be read once, the same as a response body. Streaming uploads also need the extra option duplex: 'half' and are not supported in every browser yet. Strings, FormData, Blobs, and buffers are safe to reuse in a retry, because fetch makes a new stream from them each time.
The Request Object
The Request constructor takes the same arguments as fetch(). You can use it to describe a request once and send it later, or to pass request descriptions between functions:
const request = new Request('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Draft' })
});
console.log(request.method); // 'POST'
console.log(request.headers.get('content-type')); // 'application/json'
async function send() {
const response = await fetch(request.clone());
console.log(response.status);
}When you pass both a Request and an init object, the properties in init override the matching ones on the Request. A Request with a body can be sent only once, because sending it uses up the body. Call request.clone() for each send, as the example does, if you might send it more than once.
Other Options Worth Knowing
These options show up less often but are worth recognizing:
| Option | Values | Effect |
|---|---|---|
| `cache` | `'default'`, `'no-store'`, `'reload'`, `'no-cache'`, `'force-cache'`, `'only-if-cached'` | How the request uses the browser's HTTP cache |
| `redirect` | `'follow'` (default), `'error'`, `'manual'` | What happens on a 3xx response |
| `referrerPolicy` | e.g. `'no-referrer'`, `'strict-origin-when-cross-origin'` | How much of the current URL goes in `Referer` |
| `keepalive` | `true` / `false` | Lets a small request finish after the page unloads |
| `signal` | an `AbortSignal` | Cancels the request (later chapter) |
| `mode`, `credentials` | various | Cross-origin behavior and cookies (later chapter) |
keepalive: true is useful for sending analytics when the user leaves the page. Browsers cap the total body size of in-flight keepalive requests at about 64 KB.
With redirect: 'follow', a 301 or 302 response to a POST is followed as a GET, and the body is dropped. A 307 or 308 response keeps the method and the body. If a POST seems to lose its body, look for a redirect in the network panel.
Exercise
This request reaches the server, but the server reports that req.body is empty. What is wrong, and how do you fix it? fetch('https://api.example.com/items', { method: 'post', body: JSON.stringify({ name: 'Lamp' }) })
Show answer
The body is a string, so the browser labels it text/plain;charset=UTF-8, and the server's JSON parser skips it. Add headers: { 'Content-Type': 'application/json' }. The lowercase 'post' is not the cause, because fetch uppercases POST automatically. Writing 'POST' is still good practice.
Exercise
A teammate's file upload fails with a server error saying "Multipart: Boundary not found." Their code sets headers: { 'Content-Type': 'multipart/form-data' } and body: formData. Why does it fail?
Show answer
Setting Content-Type by hand replaces the value the browser would have generated, which includes the boundary=... parameter the server needs to split the parts. Remove the Content-Type header and let the browser set it for the FormData body.
Exercise
You call fetch(url, { method: 'GET', body: JSON.stringify(filters) }) and the promise rejects before any request shows up in the network panel. What error do you get, and how should you send the filters instead?
Show answer
fetch rejects with a TypeError because GET and HEAD requests cannot have a body. Put the filters in the query string, for example by building a URL and calling url.searchParams.set(key, value) for each filter. If the API supports it, you can also switch to a POST endpoint that accepts a body.
Exercise
A PATCH request works in Postman but returns 405 from the browser. The code uses method: 'patch'. Explain the cause.
Show answer
Fetch uppercases only DELETE, GET, HEAD, OPTIONS, POST, and PUT. 'patch' is sent as lowercase patch, and because method names are case-sensitive the server does not recognize it. Change it to 'PATCH'.