AI Code

JavaScript Fetch


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


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.


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.


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

    .then(response => {
        if (!response.ok()) {
            throw new Error("Request failed!");
        return response.json();
    .then(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'


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('', {
    credentials: 'include'

Getting JSON data

// get some data from 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 =

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

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');
    const a = document.createElement('a');
    a.href = link;
    a.textContent = `[${score}] ${title} (by ${owner.display_name || 'somebody'})`

Got any JavaScript Question?