Concept Explanation
The Fetch API is the built-in browser tool for making HTTP requests (Getting data from a server or sending it). It replaced the old, clunky XMLHttpRequest (AJAX) and uses Promises natively.
Syntax or Core Structure
The Standard Pattern
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST", // GET, POST, PUT, DELETE
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "New Post", body: "Hello World" })
})
.then(res => res.json()) // Essential! Turns raw response into JS object
.then(data => console.log(data));
Status Codes
Fetch only "Rejects" if there's a network failure. It does NOT reach the .catch() if the server returns a "404 Not Found" or "500 Server Error". You must check response.ok manually!
Real World Example
Search Box: Every time you type a letter, a fetch() request is sent to the server. The server sends back a list of results, and the browser updates the UI.
Best Practices
- Check for OK: Always do
if (!response.ok) throw new Error("Server error");. - JSON conversion: Don't forget to
await response.json(). Beginners often forget that the response body is also a promise! - AbortController: Use this to "Cancel" a fetch request if the user navigates away or clicks "Cancel."
Practice Exercises
- The List Fetcher: Use the free JSONPlaceholder API (
https://jsonplaceholder.typicode.com/todos) to fetch and log the titles of the first 10 tasks. - The Poster: Write a
POSTrequest that sends a mock "User Account" object to an API. - The Status Checker: Fetch a broken URL (like
google.com/nothing) and use.statusand.okto handle the 404 error correctly.