Mastering Fetch API: POST Requests, Binary Data & Performance

Day 93 of me reading random and basic but important dev topicsss.... Today I read about the POST Requests, Binary Data & Performance in fetch() 1. Headers: Reading and Writing * Reading: response.headers gives you a Map-like object. You can easily get specific headers via response.headers.get('Content-Type') or iterate over all of them using a for...of loop. * Writing: Pass a headers object in the options parameter. Note: The browser exclusively controls certain "forbidden" headers (like Host, Origin, Referer, and Cookie) for security reasons. 2. Making POST Requests To send data, you need to add method and body to your fetch options. When sending a JSON payload, don't forget your Content-Type! By default, sending a string body sets the content type to text/plain. let user = { name: 'John', surname: 'Smith' }; let response = await fetch('/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(user) }); 3. Submitting Binary Data (Images/Files) Fetch handles binary data beautifully. You can pass a Blob or BufferSource directly to the body. If you pass a Blob (for instance, an image generated from an HTML <canvas> using canvas.toBlob), you don't even need to set the Content-Type header manually! The Blob object's built-in type (e.g., image/png) automatically becomes the Content-Type. 4. Pro-Tip: Optimizing Concurrent Fetches When fetching multiple independent endpoints, never map an array of URLs to an array of fetch() calls and then blindly await Promise.all(...) before calling .json(). Why? It forces the JSON parsing to wait for the slowest network request to finish! Instead, attach .then(res => res.json()) directly to each individual fetch promise. This ensures that as soon as any single request finishes, it immediately starts processing its JSON payload without waiting for its siblings. Keep Learning!!!! #JavaScript #WebDevelopment #SoftwareEngineering #WebPerformance #FetchAPI

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories