Table of Contents

Pengenalan

Axios adalah sebuah HTTP client library yang memungkinkan kita untuk melakukan request ke sebuah endpoint(Rest Api misal). Sebetulnya Reactjs sendiri memiliki metode bawaan bernama Fetch untuk menangani hal serupa namun tidak bisa dipungkiri bahwa kebanyakan developer menggunakan Axios dalam hal ini.

Berikut perbandingan Axios vs Fetch.

AxiosFetch
Axios has url in request object.Fetch has no url in request object.
Axios is a stand-alone third party package that can be easily installed.Fetch is built into most modern browsers; no installation is required as such.
Axios enjoys built-in XSRF protection.Fetch does not.
Axios uses the data property.Fetch uses the body property.
Axios’ data contains the object.Fetch’s body has to be stringified.
Axios request is ok when status is 200 and statusText is ‘OK’.Fetch request is ok when response object contains the ok property.
Axios performs automatic transforms of JSON data.Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the .json() method on the response.
Axios allows cancelling request and request timeout.Fetch does not.
Axios has the ability to intercept HTTP requests.Fetch, by default, doesn’t provide a way to intercept requests.
Axios has built-in support for download progress.Fetch does not support upload progress.
Axios has wide browser support.Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (This is known as Backward Compatibility).
Axios “GET” call ignores data content

Fetch “GET” call can have body content

Dari perbandingan di atas Axios memiliki cukup banyak keunggulan dalam menangani Rest API dibandingkan Fetch.

Persiapan
  1. Reactjs sudah diinstall.
  2. API sudah disiapkan.

 

Installasi
				
					cd my-app
npm install axios
				
			
Format Request
				
					import axios from 'axios';
				
			
GET
				
					axios get(url, {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json;charset=UTF-8"
    },
  })
.then(({data}) => {
    console.log(data);
}).catch(error => {
    console.error('timeout exceeded'))
})
				
			
POST
				
					axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },{
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json;charset=UTF-8"
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
				
			
PUT
				
					console.log( 'Code is Poetry' );