65.9K
CodeProject is changing. Read more.
Home

Fetch API and XMLHttpRequest

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (5 votes)

Jan 29, 2017

CPOL
viewsIcon

9410

Access the API using the promise HTTP

Introduction

Ajax changed the way of the modern web application loading partially and most of the applications are using Ajax. It can post or pull data asynchronous without reloading the entire page.

XMLHttpRequest

var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {

            if (xhr.readyState == XMLHttpRequest.DONE) {

                console.log(xhr.response);
            }
        }

        xhr.open('GET', 'http://localhost:801/api/Person', true);

        xhr.send(null);  

The above code may not work in some browser for the safe we will be using the Jquery library.

  $.ajax({
            url: 'http://localhost:801/api/Person',
            method: 'Get',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log('error');
            }
        });

The fetch method is similar to XMLHttpRequest, whereas Fetch is a promise based asynchronous http networking. It is a clean and easy way to access the API. The browsers supported are Firefox 39 and above and chrome 42 and above. For all other versions of browsers, we can use the alternate Fetch Polyfill (https://github.com/github/fetch):

fetch('http://localhost:801/api/Person').then(x => {

            return x.json();

        }).then(y => {

            console.log(y);

        });

Adding header in the fetch API.

var myHeaders = new Headers();
    var myInit = { method: 'GET',
        headers: myHeaders,
        mode: 'cors'}
    fetch('http://localhost:801/api/Person',myInit)
    .then(function(response) {
        return response.blob()
    });