Fetch API customization

The Fetch API is highly customizable. You can even include your own headers in the request. Suppose you've got a site where only authenticated users with a valid token can access an image. Here's how you'll add a custom header to your request:

const headers = new Headers();headers.append("Allow-Secret-Access", "yeah-because-my-token-is-1337");const config = { method: 'POST', headers };const req = new Request('http://myawesomewebsite.awesometld/secretimage.jpg', config);fetch(req).then(img => img.blob()).then(blob => myImageTag.src = URL.createObjectURL(blob));

Here, we added a custom header to our Request and then created something called a Request object (an object that has information about our Request). The first ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.