Fetch examples

Supplying request options

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:

See fetch()_ for the full options available, and more details.

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  return response.json(); // parses JSON response into native JavaScript objects

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `response.json()` call

Uploading JSON data

Use fetch() to POST JSON-encoded data.

 1 const data = { username: 'example' };
 3 fetch('https://example.com/profile', {
 4   method: 'POST', // or 'PUT'
 5   headers: {
 6     'Content-Type': 'application/json',
 7   },
 8   body: JSON.stringify(data),
 9 })
10 .then(response => response.json())
11 .then(data => {
12   console.log('Success:', data);
13 })
14 .catch((error) => {
15   console.error('Error:', error);
16 });

Example https://javascript.info/fetch

JavaScript can send network requests to the server and load new information whenever it’s needed.

For example, we can use a network request to:

  • Submit an order,

  • Load user information,

  • Receive latest updates from the server,

  • …etc.

…And all of that without reloading the page!

There’s an umbrella term “AJAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript.

We don’t have to use XML though: the term comes from old times, that’s why that word is there. You may have heard that term already.

There are multiple ways to send a network request and get information from the server.

The fetch() method is modern and versatile, so we’ll start with it.

It’s not supported by old browsers (can be polyfilled), but very well supported among the modern ones.

The basic syntax is:

let promise = fetch(url, [options])
  • url – the URL to access.

  • options – optional parameters: method, headers etc.

Without options, that is a simple GET request, downloading the contents of the url.

A window.fetch JavaScript polyfill https://github.com/github/fetch

The fetch() function is a Promise-based mechanism for programmatically making web requests in the browser.

This project is a polyfill that implements a subset of the standard Fetch specification, enough to make fetch a viable replacement for most uses of XMLHttpRequest in traditional web applications

fetch + get with parameters https://github.com/github/fetch/issues/256

// https://fetch.spec.whatwg.org/#fetch-api
var url = new URL("https://geo.example.org/api");
var params = {lat:35.696233, long:139.570431};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))

Example https://tobiasahlin.com/blog/move-from-jquery-to-vanilla-javascript/

// With jQuery
    url: "data.json"
  }).done(function(data) {
    // ...
  }).fail(function() {
    // Handle error
// Without jQuery
  .then(data => {
    // Handle data
  }).catch(error => {
    // Handle error