Axios tutorial

Features of axios

  1. make XMLHttpRequest from the browser

  2. make http request from node.js

  3. supports the promise api

  4. intercept the response and request

  5. transform request and response data to json format automatically

  6. cancel request

  7. Csrf attacks protections.

CSRF:

Cross-Site Request Forgery (CSRF) is a type of security vulnerability that occurs when an attacker tricks a user's browser into making an unintended and unauthorized request to a web application on which the user is authenticated. This can lead to actions being performed on behalf of the user without their consent.

Create the instance of axios

const axiosInstance = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com',
    timeout: 2000,
    headers: {
        'Content-Type': 'application/json'
    }
}); 

//now every axios request should be like
axiosInstance.get(config);

Ways to make axios request.

//using the promise for client side.
const res = axios({
     method:'get',
     url:'relative url'
)}
.then( res => console.log(res.data))// on sucessfull
.catch( err => console.log(err)) //On error
.finally(res => /*do whatever whatever be the response*/)//on everyTime

//using the async await function 
//basically for server side 
async function getData(){
try{
     const res = await axiosInstance({
            method: 'get',
            url: '/todos/a'
        })
   console.log(res.data);
 }
    catch (err) {
        console.log(err);
    }
};