1. Basic GET Request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | fetch("https://api.bytestaq.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// Async/Await
async function getData() {
try {
const res = await fetch("https://api.bytestaq.com/data");
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
|
2. Response Handling
| const res = await fetch(url);
res.ok // true if status 200–299
res.status // HTTP status code
res.headers // headers object
Body Parsers
await res.json()
await res.text()
await res.blob()
await res.arrayBuffer()
|
3. POST Request (JSON)
| fetch("https://api.bytestaq.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Alice"
})
});
|
4. PUT / PATCH / DELETE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | // PUT
fetch(url, {
method: "PUT",
body: JSON.stringify(data)
});
// PATCH
fetch(url, {
method: "PATCH",
body: JSON.stringify(data)
});
// DELETE
fetch(url, {
method: "DELETE"
});
|
| fetch(url, {
headers: {
"Authorization": "Bearer TOKEN",
"Content-Type": "application/json"
}
});
|
6. Auth Patterns
| // Bearer Token
headers: {
Authorization: `Bearer ${token}`
}
// Basic Auth
headers: {
Authorization: "Basic " + btoa("user:pass")
}
|
| const formData = new FormData();
formData.append("file", file);
fetch(url, {
method: "POST",
body: formData
});
|
Don’t set Content-Type manually (browser sets boundary)
8. Sending URL-Encoded Data
| const params = new URLSearchParams();
params.append("key", "value");
fetch(url, {
method: "POST",
body: params
});
|
9. Timeout (via AbortController)
| const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal: controller.signal })
.catch(err => {
if (err.name === "AbortError") {
console.log("Request timed out");
}
});
|
10. Error Handling Nuance
fetch only rejects on network errors, not HTTP errors.
| const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
|
11. Query Parameters
| const url = new URL("https://api.bytestaq.com");
url.searchParams.set("q", "test");
fetch(url);
|
12. Cookies & Credentials
| fetch(url, {
credentials: "include" // send cookies
});
|
Options:
- "omit" (default)
- "same-origin"
- "include"
13. CORS Basics
| fetch(url, {
mode: "cors"
});
|
Controlled by server headers (Access-Control-Allow-Origin)
Client cannot override server restrictions
14. Streaming Response
| const res = await fetch(url);
const reader = res.body.getReader();
|
Used for:
- large files
- real-time data streams
15. Retry Pattern
| async function fetchWithRetry(url, retries = 3) {
try {
return await fetch(url);
} catch (err) {
if (retries > 0) {
return fetchWithRetry(url, retries - 1);
}
throw err;
}
}
|
16. Full Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | async function request(url, options = {}) {
const res = await fetch(url, {
headers: {
"Content-Type": "application/json",
...options.headers
},
...options
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Error ${res.status}: ${text}`);
}
return res.json();
}
|
17. Common Patterns
| // Parallel Requests
const [a, b] = await Promise.all([
fetch(url1).then(r => r.json()),
fetch(url2).then(r => r.json())
]);
// Sequential
const a = await fetch(url1);
const b = await fetch(url2);
|
18. Common Mistakes
- Forgetting await res.json()
- Not checking res.ok
- Setting wrong Content-Type
- Not handling timeouts
- CORS confusion (server-side issue)
19. Quick Reference
| fetch(url, {
method: "GET | POST | PUT | DELETE",
headers: {},
body: JSON.stringify(data),
credentials: "include",
signal
});
|
Join the Newsletter
Practical insights on Django, backend systems, deployment, architecture, and real-world development — delivered without noise.
Get updates when new guides, learning paths, cheat sheets, and field notes are published.
No spam. Unsubscribe anytime.
There is no third-party involved so don't worry - we won't share your details with anyone.