Getting started with JavaScriptFunctionsArraysObjectsAJAXClassesArithmetic (Math)Comparison OperationsConditionsLoopsPromisesRegular expressionsDateError HandlingGeolocationCookiesIntervals and TimeoutsGeneratorsHistoryStrict modeCustom ElementsJSONBinary DataTemplate LiteralsWeb StorageFetchScopeModulesScreenInheritanceTimestampsDestructuring assignmentWorkersVariable coercion/conversionDebuggingNotifications APIBuilt-in ConstantsWebSocketsWeb Cryptography APIAsync functions (async/await)StringsConstructor functionsexecCommand and contenteditablePerformance TipsMapCreational Design PatternsrequestAnimationFrameReserved KeywordsMethod ChainingGlobal error handling in browsersUnary OperatorsFile API, Blobs and FileReadersCommentsConsoleTail Call OptimizationDetecting browserEnumerationsSymbolsLocalizationSelection APICallbacksSetDeclarations and AssignmentsFunctional JavaScriptModals - PromptsData attributesThe Event LoopBattery Status APIData ManipulationBitwise operatorsTranspilingBOM (Browser Object Model)Unit Testing JavascriptLinters - Ensuring code qualityAutomatic Semicolon Insertion - ASIIndexedDBAnti-patternsNavigator ObjectModularization TechniquesProxySame Origin Policy & Cross-Origin CommunicationArrow Functions.postMessage() and MessageEventWeakMapWeakSetEscape SequencesBehavioral Design PatternsServer-sent eventsAsync IteratorsNamespacingEvaluating JavaScriptMemory efficiencyDate ComparisonHow to make iterator usable inside async callback functionContext (this)Setters and GettersVibration APIPrototypes, objectsDatatypes in JavascriptBitwise Operators - Real World Examples (snippets)Fluent APITilde ~Security issuesUsing javascript to get/set CSS custom variablesJavaScript VariablesEvents

Fetch

Other topics

Remarks:

The Fetch standard defines requests, responses, and the process that binds them: fetching.

Among other interfaces, the standard defines Request and Response Objects, designed to be used for all operations involving network requests.

A useful application of these interfaces is GlobalFetch, which can be used to load remote resources.

For browsers that do not yet support the Fetch standard, GitHub has a polyfill available. In addition, there is also a Node.js implementation that is useful for server/client consistency.

In the absence of cancelable Promises you can't abort the fetch request (github issue). But there is a proposal by the T39 in stage 1 for cancelable promises.

GlobalFetch

The GlobalFetch interface exposes the fetch function, which can be used to request resources.

fetch('/path/to/resource.json')
    .then(response => {
        if (!response.ok()) {
            throw new Error("Request failed!");
        }
            
        return response.json();
    })
    .then(json => { 
        console.log(json);
    }); 

The resolved value is a Response Object. This Object contains the body of the response, as well as it's status and headers.

Set Request Headers

fetch('/example.json', {
    headers: new Headers({
        'Accept': 'text/plain',
        'X-Your-Custom-Header': 'example value'
    })
});

POST Data

Posting form data

fetch(`/example/submit`, {
    method: 'POST',
    body: new FormData(document.getElementById('example-form'))
});

Posting JSON data

fetch(`/example/submit.json`, {
    method: 'POST',
    body: JSON.stringify({
        email: document.getElementById('example-email').value,
        comment: document.getElementById('example-comment').value
    })
});

Send cookies

The fetch function does not send cookies by default. There are two possible ways to send cookies:

  1. Only send cookies if the URL is on the same origin as the calling script.
fetch('/login', {
    credentials: 'same-origin'
})
  1. Always send cookies, even for cross-origin calls.
fetch('https://otherdomain.com/login', {
    credentials: 'include'
})

Getting JSON data

// get some data from stackoverflow
fetch("https://api.stackexchange.com/2.2/questions/featured?order=desc&sort=activity&site=stackoverflow")
  .then(resp => resp.json())
  .then(json => console.log(json))
  .catch(err => console.log(err));

Using Fetch to Display Questions from the Stack Overflow API

const url =
      'http://api.stackexchange.com/2.2/questions?site=stackoverflow&tagged=javascript';

const questionList = document.createElement('ul');
document.body.appendChild(questionList);

const responseData = fetch(url).then(response => response.json());
responseData.then(({items, has_more, quota_max, quota_remaining}) => {
  for (const {title, score, owner, link, answer_count} of items) {
    const listItem = document.createElement('li');
    questionList.appendChild(listItem);
    const a = document.createElement('a');
    listItem.appendChild(a);
    a.href = link;
    a.textContent = `[${score}] ${title} (by ${owner.display_name || 'somebody'})`
  }
});

Syntax:

  • promise = fetch(url).then(function(response) {})
  • promise = fetch(url, options)
  • promise = fetch(request)

Parameters:

OptionsDetails
methodThe HTTP method to use for the request. ex: GET, POST, PUT, DELETE, HEAD. Defaults to GET.
headersA Headers object containing additional HTTP headers to include in the request.
bodyThe request payload, can be a string or a FormData object. Defaults to undefined
cacheThe caching mode. default, reload, no-cache
referrerThe referrer of the request.
modecors, no-cors, same-origin. Defaults to no-cors.
credentialsomit, same-origin, include. Defaults to omit.
redirectfollow, error, manual. Defaults to follow.
integrityAssociated integrity metadata. Defaults to empty string.

Contributors

Topic Id: 440

Example Ids: 1463,2062,2063,4957,5552,18651

This site is not affiliated with any of the contributors.