The fetch()
API is the modern way to make network requests in JavaScript. It is promise-based and provides a cleaner, more flexible way to fetch resources (like APIs) compared to XMLHttpRequest
. Let's break it down! π₯
fetch()
? π€β
fetch()
is used to make HTTP requests (GET, POST, PUT, DELETE, etc.).
β
It returns a Promise, which resolves to the Response
object.
β
Itβs more readable and flexible compared to older methods like XMLHttpRequest
.
fetch(url, options)
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Use the data
.catch(error => console.error("Error:", error)); // Handle errors
url
: The API or resource URL.options
: (Optional) An object specifying HTTP method, headers, body, etc.fetch("<https://jsonplaceholder.typicode.com/posts/1>")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Output the data
.catch(error => console.error("Error fetching data:", error));
Output:
{
"userId": 1,
"id": 1,
"title": "Sample Post",
"body": "This is a sample post content."
}
π fetch()
does NOT reject on HTTP errors (like 404 or 500)! You must check response.ok
manually.
fetch("<https://jsonplaceholder.typicode.com/invalid-url>")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error));