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! πŸ”₯


πŸ”Ή What is 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.


πŸ”Ή Basic Syntax

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


πŸ”Ή Making a Simple GET Request

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));