The Web Dev Guide by Wishtack
  • The Web Dev Guide by Wishtack
  • HTML
    • HTML Tags
    • HTML Attributes
    • Content Formatting
    • Empty Tags vs Content Tags
    • Some Links
  • ECMAScript
    • Some History
    • Language Properties
    • Single-Threaded thus Asynchronous
    • The Event Loop
    • Classes
    • Hoisting is Dead: var vs. let vs. const
    • this & "binding"
    • Arrow Functions
    • Template Strings
    • Syntactic Sugar
      • Spread
      • Destructuring
      • Rest
      • Object Literal Property Value Shorthand
    • Named Parameters
    • Compatibility
  • Tools
    • Node.js
    • NPM
    • Yarn
    • Webpack
    • WebStorm
    • StackBlitz
  • DOM
    • What Is It?
    • Element Selection
    • Element Modification
    • Events
  • Forms
    • The <form> tag
    • Form elements
    • Form validation
  • Networking
    • Fetch Web API
  • CSS
    • Selectors
    • Transforms
    • Transitions
    • Animations
    • Web Animations API
    • Sass
  • Responsive Web Design
    • Viewport
    • Media Queries
    • Grid Layout
    • Flex Layout
    • Frameworks & Libraries
  • Web APIs
  • Testing
    • Unit Testing
    • End to End Testing
  • Security
    • Injection
    • DOM XSS
    • Insecure Direct Object Reference
    • Cross-Site Request Forgery
    • Client vs API Validation
    • API Unauthorized Access and Data Leak
  • More Links
Powered by GitBook
On this page
  • fetch usage
  • fetch options
  1. Networking

Fetch Web API

Luckily, thanks to the fetch Web API and without any external library, we will not need to use the old fashioned XMLHttpRequest object.

const xmlHttpRequest = new XMLHttpRequest();

xmlHttpRequest.onreadystatechange = () => {
    if (xmlHttpRequest.readyState === 4 /* request is complete */
        && xmlHttpRequest.status === 200) {
        document.querySelector('.wt-wish-list').innerHTML = xmlHttpRequest.responseText;
    }
};

xmlHttpRequest.open('GET', '/users/123456/wishes/', true /* async */);

xmlHttpRequest.send();

fetch usage

The fetch() function returns a Promise<Response> (a promise that resolves to a Response object).

The Response.json() method returns a Promise that resolves the object produced by parsing the JSON content of the body.

fetch('https://www.googleapis.com/books/v1/volumes?q=extreme%20programming')
    .then(response => response.json())
    .then(data => console.log(data));

Or using async/await:

const response = await fetch('https://www.googleapis.com/books/v1/volumes?q=extreme%20programming');
const data = await response.json();
console.log(data);

fetch options

The second argument for the fetch function is an options object that allows you for instance to send POST requests or to control additional stuff in the request like HTTP headers.

const book = {
    id: 'BOOK_ID',
    title: 'eXtreme Programming explained'
};

fetch('https://api.mylibrary.io/books', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify(book)
});

In order to avoid security issues like URL forgery, it is recommended to encode the dynamic parts of the URL when constructing it using the encodeURIComponent function.

const uri = `https://api.mylibrary.io/books/${encodeURIComponent(bookId)}`;

PreviousNetworkingNextCSS

Last updated 6 years ago