JavaScript Fetch API
The Fetch API is a modern way to make HTTP requests in JavaScript. It replaces older methods like XMLHttpRequest and is based on Promises, making it cleaner and more powerful for working with APIs.
Basic Syntax of Fetch
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:"
, error));
- fetch() returns a Promise
- .then(response => response.json()) parses the response body
- .catch() handles any network or parsing errors
Example: GET Request
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log("Post title:"
, data.title))
.catch(error => console.error("Error:", error));
Output
Post title: sunt aut facere repellat provident occaecati...
Example: POST Request (Sending Data)
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "New Post",
body: "This is the content",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log("Created:", data))
.catch(error => console.error("Error:", error));
Using async/await with Fetch
async function fetchPost() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log("Post title:" , data.title);
} catch (error) {
console.error("Fetch error:", error);
}
}
fetchPost();
Handling Errors Properly
Even if the server returns a 404 or 500, fetch() doesn’t throw an error. You must manually check response.ok.
async function fetchData() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/invalid-url");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Fetch failed:", err.message);
}
}