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).

Values:

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

https://github.com/github/fetch

See

In the Browser devtool, you can see them.

Example with Chrome.

Chrome Devtool Xhr Fetch Request

Example

See mdn/fetch-examples

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

A post that sends form-urlencoded data.

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

See mdn/fetch-examples

Wrapper Library

isomorphic-unfetch

npm install --save isomorphic-unfetch

Documentation / Reference





Discover More
Chrome Devtool Xhr Fetch Request
Browser - Ajax (Asynchronous JavaScript And XML)

Asynchronous Javascript and XML (Ajax) is just a name umbrella to talk a technology that retrieve data from a server asynchronously. Ajax Every Ajax call is using: a XMLHttpRequest (XHR) request...
Browser
Browser - Fetching Resources (Request/Response)

This article is fetching (http request/response) in the browser. User agents can implement a variety of transfer protocols to fetch resources such as: HTTP : , ... Form FTP ... rendering...
Chrome Devtool Xhr Fetch Request
Browser - XMLHttpRequest (XHR) API

The XMLHttpRequest is a web api function that performs an resource fetch with an Aysnchronous HTTP request XMLHttpRequestAPIAJAX programmingfetch API The status of an XHR request. Value Constant...
Blob Url In Browser Address
Browser / Javascript - Object URL (createObjectURL / revokeObjectURL)

An ObjectUrl is the representation of blob object as a data URL strings that can be used with any fetch HTML element that accepts an URL as an attribute. HTML Example: This HTML was generated with...
Recaptcha
How can I protect myself from Bad Bot (Spambot, Attacker )?

Bad Bots are robots with bad intentions. They are also known as attackers. They walk through: web pages trying to find a form and to fill them trying: to send email in mass to create a fake...
How to manipulate a Binary large object (BLOB) with Javascript?

The blob object is a data container for blob content This is the API to work with binary data in the browser and is widely supported Because any type of data is...
How to preload HTML resource (Javascript, StyleSheet)

This article shows you how to preload HTML resources to use them at a later time.
Formdata Browser Devtool
How to use FormData and send multipart-data in the Browser (Web API )?

FormData is a web api object that represent the data of a form that should be send if the form is submited. Therefore if you have a checkbox that is not checked, formdata will not collect it. You can...
Cors Flowchart
Browser - Cross Origin Resource Sharing (CORS)

Cross-origin resource sharing (CORS) is a mechanism that: allows a HTTP server to control the cross-origin requests executed by a browser. In short, a HTTP server may allow or not to receive cross-origin...
What is the HTML crossorigin attribute ? (CORS policy)

crossorigin is an attribute that set the mode of the request to an HTTP CORS Request. Its value defines further the CORS policy. It can be used on every html elements that fetch resources from a cross-origin...



Share this page:
Follow us:
Task Runner