Sub topic 5
Configuring Requests: Methods, Headers, and Bodies
This chapter assumes you can call fetch(), check response.ok, and read a body with response.json(). It also assumes you know what HTTP methods and headers are. Until now, every request has been a plain GET. Here you will learn how to describe any request using the second argument to fetch().
The init object
fetch(resource, init) takes an optional second argument, often called the init object. It is a plain object, and its properties describe the request. The three you will use most often are listed below.
| Option | Purpose | Default |
|---|---|---|
| `method` | The HTTP method, such as `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, or `'DELETE'` | `'GET'` |
| `headers` | Request headers, given as a plain object, an array of pairs, or a `Headers` instance | none |
| `body` | The request payload: a string, `FormData`, `URLSearchParams`, `Blob`, `ArrayBuffer`, or stream | none |
There are other options too, such as signal, credentials, mode, and cache. Later chapters cover the ones that matter most.
Choosing a method
Set method to tell the server what you want to do. Method names are case-sensitive in HTTP. fetch uppercases the standard ones for you (get, post, put, delete, head, options), but it sends patch exactly as written. Some servers reject a lowercase patch, so always write method names in uppercase.
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}`);
}
// Many APIs reply to DELETE with 204 No Content, which has no body to parse.
return response.status === 204 ? null : response.json();
}Adding headers
For simple cases, a plain object is enough. The keys are header names and the values are strings.
const response = await fetch('https://api.example.com/me', {
headers: {
Accept: 'application/json',
Authorization: 'Bearer TOKEN'
}
});The browser adds some headers itself, such as User-Agent, Host, and Cookie, and it does not let your script set them. Browsers call these forbidden header names. If you try to set one, the browser quietly drops it and does not throw an error. If a header seems to be missing on the server, open the network panel and check which headers were actually sent.
Sending a body
The body option carries data to the server. Its type matters, because fetch uses it to pick a default Content-Type:
- A string defaults to
text/plain;charset=UTF-8. URLSearchParamsbecomesapplication/x-www-form-urlencoded;charset=UTF-8.FormDatabecomesmultipart/form-datawith a generated boundary.- A
Blobuses the blob's owntype, if it has one.
Here is a PUT request that replaces a resource. Because the body is a string, you must set Content-Type yourself so the server reads it as JSON. The next chapter covers JSON and form data in detail.
async function replacePost(id, post) {
const response = await fetch(`https://api.example.com/posts/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}Common mistakes
- Passing an object as the body.
body: { title: 'Hi' }is converted to the string"[object Object]". Serialize the object first. - Forgetting
Content-Typeon a string body. The server receivestext/plainand may ignore the payload or answer with 415 Unsupported Media Type. - Setting
Content-Typeby hand forFormData. If you do, the boundary parameter is lost and the server cannot parse the parts. Leave the header out and letfetchset it. - Reusing a stream body. A
ReadableStreambody can be sent only once. If you need to retry, create a new body.
Reusing a configuration with Request
You can also build a Request object from the same two arguments and pass it to fetch(). This is useful when you want to inspect or log a request before sending it.
const req = new Request('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Draft' })
});
console.log(req.method, req.headers.get('content-type'));
const response = await fetch(req);Exercise
This code sends a request but the server says it received no usable data: fetch('/api/notes', { method: 'POST', body: { text: 'Buy milk' } }). Name the two problems and fix the call.
Show answer
The body is a plain object, so fetch converts it to the string "[object Object]". And because the body is a string, the Content-Type header defaults to text/plain. The fix is: fetch('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Buy milk' }) }).
Exercise
What happens when you call fetch('/api/search', { body: 'q=fetch' }), and why?
Show answer
The promise rejects with a TypeError and no request is sent. With no method given, the method defaults to GET, and a GET request cannot have a body. Move the data into the URL instead, for example '/api/search?q=fetch'.