đ Fetch API â Modern Way to Make HTTP Requests in JavaScript
The Fetch API is a built-in browser interface that lets you make network requests (like GET, POST, PUT, DELETE) in a clean, promise-based way.
đ§ It’s a replacement for
XMLHttpRequest
, and is now the standard for fetching data in modern web apps.
đč Basic Syntax
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
đ GET Request Example
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => {
console.log('Post:', data);
});
â
Default method is GET
â
Parses response as JSON
đ POST Request Example
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Post',
body: 'Hello World!',
userId: 1
})
})
.then(res => res.json())
.then(data => {
console.log('Created:', data);
});
âïž Common Options in fetch()
Option | Use |
---|---|
method | 'GET' , 'POST' , 'PUT' , 'DELETE' , etc. |
headers | Add custom request headers |
body | Send data (for POST/PUT), usually as JSON |
credentials | 'include' to send cookies |
mode | 'cors' , 'no-cors' , 'same-origin' |
đ§ Handling Response
fetch('/api/data')
.then(res => {
if (!res.ok) {
throw new Error('Network error');
}
return res.json(); // or res.text(), res.blob(), etc.
})
.then(data => console.log(data))
.catch(err => console.error(err));
đ With Authentication (Token)
fetch('/api/user', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
}
})
.then(res => res.json())
.then(user => console.log(user));
đ Async/Await Version
async function getPost() {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
console.log(data);
} catch (error) {
console.error('Fetch failed:', error);
}
}
đ CORS & Credentials
To send cookies or HTTP auth:
fetch('/secure-endpoint', {
credentials: 'include'
});
For CORS requests, your backend must handle proper headers:
Access-Control-Allow-Origin: https://yourdomain.com
Access-Control-Allow-Credentials: true
â Summary
Feature | Description |
---|---|
Promise-based | Cleaner than XHR |
Built-in | No libraries needed |
Supports async/await | â |
Handles all HTTP verbs | â |
Used for APIs & RESTful calls | â |
đ Bonus Resources
Mockaroo for fake APIs
Here are three options based on what you might want to build with the Fetch API. You can pick any or all of them:
â 1. đ Reusable Fetch Wrapper Function
A utility to simplify repeated fetch requests:
// utils/fetchHelper.js
export async function fetchAPI(url, method = 'GET', data = null, token = '') {
const options = {
method,
headers: {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
},
...(data && { body: JSON.stringify(data) }),
};
try {
const res = await fetch(url, options);
if (!res.ok) throw new Error(`Error: ${res.status}`);
return await res.json();
} catch (err) {
console.error(‘Fetch error:’, err);
throw err;
}
}
Usage:
const post = await fetchAPI('/api/posts/1');
const newPost = await fetchAPI('/api/posts', 'POST', { title: 'Hello' });
â
2. âïž React App Example Using fetch()
import { useEffect, useState } from 'react';
export default function PostList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch(‘https://jsonplaceholder.typicode.com/posts’)
.then(res => res.json())
.then(data => setPosts(data.slice(0, 5))) // Get first 5
.catch(err => console.error(err));
}, []);
return (
<ul>
{posts.map(post => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
);
}
â
Ideal for React beginners
â
Can be extended with loading/spinner, error states
â 3. đŠ Real-World CRUD Example (HTML + Fetch + Backend)
HTML
<form id="postForm">
<input type="text" name="title" placeholder="Post title" required />
<textarea name="body" placeholder="Post content" required></textarea>
<button type="submit">Add Post</button>
</form>
<div id="output"></div>
JS
const form = document.getElementById('postForm');
const output = document.getElementById('output');
form.addEventListener(‘submit’, async (e) => {
e.preventDefault();
const title = form.title.value;
const body = form.body.value;
const res = await fetch(‘https://jsonplaceholder.typicode.com/posts’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ title, body }),
});
const data = await res.json();
output.innerHTML = `<p>â
Post created: ${data.title}</p>`;
});