Docs

Everything You Need to Know

Fetch

API

fetch

fetch(url)

Fetch is a method for access a remote server. You use this like you would the XMLHttpRequest object. In face, ChocolateChip-UI has a polyfill that uses XMLHttpRequest behind the scenes to implement fetch. Currently fetch support is spotty in browsers.

Fetch can perform your basic CRUD operations. Fetch takes two arguments, an input (url) and an init object of key value pairs. If you are getting data from a server, you can just provide the url and use promise chaining to handle the result:


fetch('my/url/stuff')
  .then(function(response) {
    response.json()
      .then(function(data) {  
        console.log(data);  
      });
  });

// ChocolateChip-UI can simplify the JSON parsing
// with a dedicated JSON parser:
fetch('my/url/stuff')
  .then($.json)
  .then(function(data) {  
    console.log(data);  
  });

As we mentioned, you can provide of second argument of key value pairs. Here are the possible values you can use when creating a fetch request:

init: {
  method: {
    'GET',
    'POST',
    'PUT',
    'DELETE',
    'OPTIONS',
    'HEAD'
  },
  headers: {
    'Accept': 'application/json',
    'Accept-Encoding', 'deflate',
    'Accept-Encoding', 'gzip'
    'Content-Type': 'application/json',
    "Content-Type": "application/x-www-form-urlencoded",
    'Content-Type', 'image/jpeg',
    'Content-Type', 'text/html'
  },
  body: {
    json,
    text,
    formData,
    blob,
    arrayBuffer
  },
  mode:  {
    "cors",
    "no-cors",
    "same-origin",
  },
  credentials: {
    "omit",
    "same-origin",
    "include"
  },
  cache: {
    "default",
    "no-store",
    "reload",
    "no-cache",
    "force-cache",
    "only-if-cached"
  },
  timeout: 10000
}

fetch

fetch.then

fetch.then(callback)

This method allows you to chain results of a fetch request to handle it. A single then might be sufficient for your needs, or you may want to break down what you are doing into multipe thens by returning a promise in each one. Using then allows you to have a number of operations, each dependent on the result of the previous, without dealing with nested callbacks.


fetch('my/url/stuff')
  .then(function(response) {
    console.log(response.text());
  });

// Chained thens:
fetch('my/url/stuff')
  .then($.json)
  .then(function(data) {  
    console.log(data);  
  });

fetch.catch

fetch.catch(callback)

This method is used on a fetch object to handle errors. Even though it handles errors, it is chainable with other thens, allows you to do something after handling the error:


fetch('my/url/stuff')
  .then($.json)
  .then(function(data) {  
    console.log(data);  
  })
  .catch(function(err) {
    console.log(err);
  });

// Chain a then after a catch:
fetch('my/url/stuff')
  .then($.json)
  .then(function(data) {  
    console.log(data);  
  })
  .catch(function(err) {
    console.log(err);
  })
  .then(function() {
    // Do something else because
    // there was an error.
  })

Headers

Headers.Headers()

This method creates a new Headers object.


var headers = Headers.Headers();

Headers.append

Headers.append()

Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.


var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');

Headers.delete

Headers.delete()

Deletes a header from a Headers object.


myHeaders.delete('Content-Type')

Headers.get

Headers.get()

Returns the first value of a given header from within a Headers object.


var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
myHeaders.get('Content-Type'); // Returns 'image/jpeg'

Headers.getAll

Headers.getAll()

Returns an array of all the values of a header within a Headers object with a given name.


var myHeaders = new Headers();
myHeaders.append('Accept-Encoding', 'deflate');
myHeaders.append('Accept-Encoding', 'gzip');
// Returns [ "deflate", "gzip" ]:
myHeaders.getAll('Accept-Encoding');

Headers.has

Headers.has()

Returns a boolean stating whether a Headers object contains a certain header.


var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
myHeaders.has('Content-Type'); // Returns true
myHeaders.has('Accept-Encoding'); // Returns false

Headers.set

Headers.set()

Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.


var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
// Change the content type to text:
myHeaders.set('Content-Type', 'text/html');

Request.Request

Request.Request(input, init)

Creates a new Request object. input defines the resource that you wish to fetch. This can either be:

  • A USVString containing the direct URL of the resource you want to fetch.
  • A Request object.

init is an options object containing any custom settings that you want to apply to the request. The possible options are:

  • method: The request method, e.g., GET, POST.
  • headers: Any headers you want to add to your request, contained within a Headers object or ByteString.
  • body: Any body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that a request using the GET or HEAD method cannot have a body.
  • mode: The mode you want to use for the request, e.g., cors, no-cors, or same-origin.
  • credentials: The request credentials you want to use for the request: omit, same-origin, or include.
  • cache: The cache mode you want to use for the request: default, no-store, reload, no-cache, force-cache, or only-if-cached.
  • redirect: The redirect mode to use: follow, error, or manual.

Response.Response

Response.Response()

Creates a new Response object. This takes two arguments, body and init. Body is an object defining a body for the response. This can be one of:

  1. Blob
  2. BufferSource
  3. FormData
  4. URLSearchParams
  5. USVString

init is an options object containing any custom settings that you want to apply to the response. The possible options are:

  1. status: The status code for the reponse, e.g., 200.
  2. statusText: The status message associated with the staus code, e.g., OK.
  3. headers: Any headers you want to add to your response, contained within a Headers object or object literal of ByteString key/value pairs (see HTTP headers for a reference).

var myResponse = new Response(body, init);

Response.clone

Response.clone()

Creates a clone of a Response object.


var response2 = response1.clone();

Response.error

Response.error()

Returns a new Response object associated with a network error.


var errorResponse = response.error();

Response.redirect

Response.redirect(url, status)

Creates a new response with a different URL. This can take up to two arguments. First, the URL that the new response is to originate from. Second, you can pass an optional status code for the response (e.g., 302.)


var response2 = response1.redirect(url,status);

Body.arrayBuffer

Body.arrayBuffer()

Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.


response.arrayBuffer().then(function(buffer) {
  // do something with buffer
)};

Body.blob

Body.blob()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.


response.blob().then(function(myBlob) {
  // do something with myBlob
});

Body.formData

Body.formData()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.


response.formData().then(function(formdata) {
  // do something with your formdata
});

Body.json

Body.json()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a JSON object.


response.json().then(function(json) {
  // do something with your JSON
});

Body.text

Body.text()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text).


response.text().then(function (text) {
  // do something with the text response 
});

$.jsonp

$.jsonp(url, options)

Although Fetch does not have support for JSONP, ChocolateChipJS provides a Fetch-like API for doing JSONP. It uses the $.jsonp method, which takes two arguments, a url and an object of key values. The possible keys are:

  1. timeout: a number in milliseconds
  2. callbackName: a name for the callback to use in the request
  3. clear: whether to clear out any previous requests from the global $.JSONPCallbacks object.

$.jsonp('https://something/is/here?name=chipper', { timeout: 10000 })
.then($.json)
.then(function(obj) {
  console.log(obj)
  obj.forEach(function(repo) {
    $('#message_ajax').append("
  • " + repo.name + "
  • "); }); }) .catch(function(error) { $('#message_ajax').append("
  • " + error.message + "
  • ") });