JavaScript Fetch API
Modern web applications feel snappy and responsive because they exchange data with servers in the background. The Fetch API provides a modern, powerful, and flexible interface for fetching resources asynchronously across the network.
Anatomy of a GET Request
By default, calling fetch() with a URL string makes an HTTP GET request. Since network requests take time to travel across the internet and back, fetch returns a Promise.
Using async/await makes reading these promises much cleaner. First, you await the response stream, then you await the parsing of that stream (usually into JSON).
Error Handling and response.ok
A common trap for beginners is assuming that a 404 (Not Found) or 500 (Server Error) will throw an error in the catch block. It won't. Fetch only rejects if the actual network fails (e.g., you lose internet connection).
To properly handle errors, you must manually check the response.ok boolean. If it's false, you throw an Error yourself so it goes to your catch block.
Sending Data (POST)
To send data, you must provide an options object as the second argument to fetch. You declare the method: 'POST', tell the server what format you are sending using the Headers, and attach your data to the body after stringifying it.
View Deep Dive: CORS+
Cross-Origin Resource Sharing (CORS) is a security mechanism enforced by browsers. It stops evil-site.com from fetching your banking data on bank.com. When you fetch an API on a different domain, the server must explicitly return headers allowing your origin. If not, the browser will block the response, resulting in a CORS error.
