Fetch API

Fetch API is Promise based api used to fetch resource across web server, almost same like AJAX but with easy syntax and more powerful features.

Fetch API can also send and receive data like XML, JSON, TEXT and HTML from web server without reloading.

fetch api was introduced in ES6. For IE and legacy browser, we can still use XMLHttpRequest.

Fetch Vs Ajax

PropertiesFetchAjax ( xhr)
ECMA Version ES6 ES5
Architecture Promise based Event Based
Complexity Easy Complex
Syntax Simple Verbose
Request / Response Supports Supports but complex structure
Cookies send cookies Cookie less

Fetch

fetch api is based on Request and Response . Request is the incoming stream to server and Response is the outgoing stream from server.

Request is the URL orf resource.

then handler is used to get response of request. then includes a callback with Response.

fetch example


    fetch(Request)

fetch example with then handler


    fetch(Request).then(Response=>Response.text()).then(Response=>console.log(Response));

Request

Request is the incoming stream to the server. The first Parameter URL is compulsory. Second parameter is optional with options like http method, payload, etc.

Promise {<pending>}

[[Prototype]]: Promise

  [[PromiseState]]: "fulfilled"

[[PromiseResult]]: Response


    fetch('data.txt');

fetch with options

Promise {<pending>}

[[Prototype]]: Promise

  [[PromiseState]]: "fulfilled"

[[PromiseResult]]: Response


    fetch('data.txt',{method:"GET"});

fetch with payload

Promise {<pending>}

[[Prototype]]: Promise

  [[PromiseState]]: "fulfilled"

[[PromiseResult]]: Response


fetch('/postdata',{method:'POST',body:JSON.stringify({"name":"username"})});

Response

fetch api returns a Promise that resolves to Response of that request. This will even respond to HTTP Errors like 404 () Page not Found) or 500 ( Internal Server error). For such errors, the then() handler must check Response.ok or Response.status.

Response {type: 'basic', url: 'http://127.0.0.1:5501/data.txt', redirected: false, status: 200, ok: true, …}


    fetch("data.txt").then(i=>i).then(i=>console.log(i));

Response.text()

Hello Fetch API


    fetch("data.txt").then(i=>i.text()).then(i=>console.log(i));

Response.ok

response.ok return boolean value true or false. If the resource is found successfully, the true else false. See examples below.

true


    fetch("data.txt").then(i=>i.ok).then(i=>console.log(i));

false


    fetch("abc.txt").then(i=>i.ok).then(i=>console.log(i));

Response.status

Response.status return the HTTP Response of request, like 200, 404, 500 etc. See examples below.

200


    fetch("data.txt").then(i=>i.status).then(i=>console.log(i));

404


    fetch("abc.txt").then(i=>i.status).then(i=>console.log(i));

Fetch text data

To fetch text data, use Response.text() method in first then() handler with callback and Response parameter. This will convert Response data to string. To print string response, use another then() handler with callback and Response parameter.

text from data


    fetch("data.txt").then(i=>i.text()).then(i=>document.querySelector(".app").textContent=i);

Fetch JSON data

To fetch JSON data, use Response.json() method in first then() handler with callback and Response parameter. This will convert Response data to JSOn Object. To print JSON response, use another then() handler with callback and Response parameter.

JSON data


    fetch("data.json").then(i=>i.json()).then(i=>{
        for( let j in i){
            console.log(j, i[j]);
        }
    });