Browser - Web API - Fetch function

About

The fetch function is part of the web api function and is a AJAX call. It's one of the possibilities to fetch a resource.

This is a new interface with more control than the XMLHttpRequest (XHR)

The fetch function returns a promise as response.

The Fetch Standard defines the fetch() JavaScript API

It exposes most of the networking functionality at a low level of abstraction.

Syntax

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

Then

fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *same-origin
    redirect: 'follow', // *manual, error
    referrer: 'no-referrer', // *client
    credentials: 'same-origin'
  })
  .then(
        function(response) {

        if (response.status !== 200) {
            console.log('Bad request, status Code is: ' + response.status);
        return;
        }

        // Response properties
        console.log(response.headers.get('Content-Type'));
        console.log(response.headers.get('Date'));
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.type); //  "basic", "cors" or "opaque"
        console.log(response.url);

        // Parses response data to JSON
        //   * response.json() 
        //   * response.text() 
        // are promise, you need to pass them to a callback to get the value
        response.json().then(function(data) {
            console.log(data);
        });

        }
    ) 
  .catch(function(err) {
    console.log('Fetch Error', err);
  }

Async / Await

async await syntax

with the URL api

let url = new URL('https://hostname/endpoint);
url.searchParams.set("key", "value: );
let response = await fetch(url.toString(), {method: "GET"});
if (response.status !== 200) {
    console.log('Bad request, status Code is: ' + response.status);
    return {};
}
// Parses response data:
//   * response.json() to get an object
//   * response.text() to get a text
let jsonObject = response.json();

Request

The request is specified in the first block of the fetch statement and has properties.

Credentials

Credentials are HTTP cookies, TLS client certificates, and authentication entries (for HTTP authentication). For CORS requests, use the “include” value to allow sending credentials to other domains:

Mode

Mode possible values:

Upon success, fetch will return an opaque filtered response. ie a no-cors mode will give you an opaque response, which doesn't seem to return data in the body. See Opaque Response

  • same-origin: Used to ensure requests are made to same-origin URLs
  • cors: Makes the request a CORS request.
  • navigate: This is a special mode used only when navigating between documents.
  • websocket: This is a special mode used only when establishing a WebSocket connection.

For an HTML element that fetch resources (such as javascript, stylesheet), you can set the mode with the crossorigin attribute

Management

Polyfill

See

In the Browser devtool, you can see them.

Example with Chrome.

_

Example

Get

With get, you need to use the url web api object to construct your URL.

response.text() return a promise, you need to resolve it

var url = new URL("/doc/api/weather",window.parent.location.href);
url.searchParams.set("country", "Netherland");
fetch(url.toString(), {
    method: 'GET', // *GET, PUT, DELETE, etc.
  })
  .then(function(response) {
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.type);
    console.log(response.url);
    // Response text is a promise, you need to pass it to a callback to resolve it
    response.text().then(function(data) {
            console.log(data);
    });
})

Post

var data = { name: "Foo", age: 46, city: "Oegstgeest" }

var formData = new URLSearchParams();
formData.append('json', JSON.stringify(data));

fetch('aURL', {
    body: formData, 
    cache: 'no-cache', 
    credentials: 'same-origin', 
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    method: 'POST', 
    mode: 'no-cors', 
    redirect: 'follow',
    credentials: 'same-origin'
  })
  .then(response => console.log(response)) 

or

fetch(url, {
    method: 'post',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'foo=bar&lorem=ipsum'
  })
  .then(response => response.json())
  .then(function (data) {
    console.log('Request succeeded with JSON response', data);
  })
  .catch(function (error) {
    console.log('Request failed', error);
  });

More

Wrapper Library

isomorphic-unfetch

npm install --save isomorphic-unfetch

Documentation / Reference


Powered by ComboStrap