JavaScript fetch()

const fetchData = (url, userOptions = {}) => {
    const defaultOptions = {
        method: 'POST',
        credentials: 'same-origin',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json',
            'LoginToken': 'l0g1n-t0k3n'
        }
    };
    // const options = jQuery.extend(defaultOptions, userOptions);
    const options = Object.assign({}, defaultOptions, userOptions);
    return fetch(url, options);
};

// Usage
fetchData(url)
    .then(response => response.json())
    .then(response => {
        console.log(response);
    })
    .catch(error => console.error('Error: ', error));

fetchData(url, {method: 'GET'})
    .then((response) => {
        return response.text();
    })
    .then(response => {
        let $responseContent = $(response).find('.content').html();
        $('.content').html($responseContent);
    })
    .catch(error => console.error('Error: ', error));

All fetch() parameters:

return 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; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })

fetch() example - http://jsfiddle.net/62s1tyob/

const number = document.getElementById('number');
const submit = document.getElementById('submit');
const content = document.getElementById('content');

submit.addEventListener('click', () => {
  const num = number.value;

  if (!!num) {
    fetch(`http://numbersapi.com/${num}`)
      .then(response => response.text())
      .then(text => {
        content.innerHTML = text;
      })
      .catch(error => {
        console.log(error);
      });
  }
});

html:

<input id="number" type="number" value="25" />
<button id="submit">Get Fun Fact!</button>
<p id="content"></p>

Leave a Reply

Your email address will not be published. Required fields are marked *