(Mastering GET, POST, PUT, DELETE requests and advanced fetch handling)
The Fetch API is a modern interface for making HTTP requests in JavaScript. It returns a Promise and is more powerful and flexible than older methods like XMLHttpRequest.
fetch(url, {
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
headers: {},
body: JSON.stringify(data) // for POST/PUT
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));| Method | Use Case |
|---|---|
GET | Retrieve data |
POST | Send new data |
PUT | Update existing data |
DELETE | Remove data |
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json())
.then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "My Post",
body: "Hello World",
userId: 1
})
})
.then(res => res.json())
.then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
id: 1,
title: "Updated Title",
body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
id: 1,
title: "Updated Title",
body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));fetch("https://api.example.com/data", {
headers: {
"Authorization": "Bearer your_token_here"
}
});fetch("/page.html")
.then(response => response.text())
.then(html => document.body.innerHTML = html);Fetch does not throw errors for HTTP status codes like 404 or 500. You must handle them:
fetch("/notfound")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error("Fetch error:", err));async function getData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) throw new Error("Request failed");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}fetch() function is used to perform all kinds of HTTP requests..ok to catch non-200 status errors.async/await for cleaner syntax.async/await to fetch and display data on page load.