Sunday, 16 July 2017

Introduction to fetch() 

 

fetch ()allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

 

⟹Basic Fetch Request


 Let's start by comparing a simple example implemented with an XMLHttpRequest and then with fetch. We just want to request a URL, get a response and parse it as JSON.


⟹XMLHttpRequest

function reqListener() {
var data =JSON.parse (this.responseText);
console.log(data);

function reqError (err){
console.log('Fetch Error :-s', err);
}

var oReq = new XMLHttpRequest ();
oReq.onload = reqListener;
oReq.onerror = reqListenr;
oReq.open('get' , './api/some.json' , true);
oReq.send();
 
 

 

⟹Fetch

Our fetch request looks a little like this:

fetch('./api/some.json')
.then(
  function(response) {
    if (response.status !== 200){
      console.log('Looks like there was a problem.Status Code; '  + response.status);
         return;
        }     
//Exmine the text in the response
 response.json() . then(function(data) {
console.log(data);
});
})
.catch(function(err) {
console.log('Fetch Error :-s', err);
});
       

⟹Response Metadata

In the previous example we looked at the status of the Response object as well as how to parse the response as JSON. Other metadata we may want to access, like headers, are illustrated below.

fetch ('users.json').then(function(response) {
  console.log(response.headers.get(Ccontent-Type'));
  console.log(response.headers.get('Date'));

  console.log(response.status);
  console.log(response.statusText);
  console.log(response.type);
  console.log(response.url);
});

 

⟹Chaining Promises

One of the great features of promises is the ability to chain them together. For fetch, this allows you to share logic across fetch requests.
If you are working with a JSON API, you'll need to check the status and parse the JSON for each response. You can simplify your code by defining the status and JSON parsing in separate functions which return promises, freeing you to only worry about handling the final data and the error case.

function status (response) {
if (response.status >= 200 && response.status < 300) {
   return Promise.resolve(response)
} else {
   return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}
fetch ('user.json')
.then(status)
.then(json)
 .then(function(data) {
console.log('Request succeeded with JSON response' , data);
}).catch(function(error) {
console.log('Request failed' , error);
 });





⟹POST Request

It's not uncommon for web apps to want to call an API with a POST method and supply some parameters in the body of the request.
To do this we can set the method and body parameters in the fetch() options.


fetch (url, {
    method: 'post' ,
     headers: 'post',
     ''Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
}) 

.then(json)
.then(function (data) {
   console.log('Request succeeded with JSON response' , data);
})
.catch(function (error) {
  console.log('Request faild' , error);
});

Sending Credentials with a Fetch Request

Should you want to make a fetch request with credentials such as cookies, you should set the
credentials of the request to "include".

fetch (url, {
credentials: 'include'
})

 



 

No comments:

Post a Comment

Machine Learning Annotation Introduction

Data annotation in Machine Learning is the process of annotating/ labeling data to categorize the dataset to identify by ML models. It can b...