Home

WayneCarl Barker's Portfolio/ Blog

Go Back

Axios, a Better Way to Fetch

WayneCarl

October 22, 2022

axios

get request (default)

import axios from 'axios';

const GetRequest =() =>{
    const fetchData = async () =>{
        try{
            const response =await axios(url);
            const data = response.data;
            // axios puts response on the data key
        }catch(error){
            console.log(error.response)
        }
    }
}

Request Headers

import axios from 'axios';

const GetRequest =() =>{
    const fetchData = async () =>{
        try{
            const response =await axios(url, {
                headers: {
                    Accept: 'application/json',
                },
            });
            const data = response.data;
            // axios puts response on the data key
        }catch(error){
            console.log(error.response)
        }
    }
}

Post Request

import axios from 'axios';

const GetRequest =() =>{
    const fetchData = async () =>{
        try{
            const response =await axios(url, { name, email}, {/*request headers will go hear*/});
            const data = response.data;
            // axios puts response on the data key
        }catch(error){
            console.log(error.response)
        }
    }
}

Setting Up Global axios

In a file axios/global.js for example Note there are other things you can set globally

import axios from 'axios';

axios.defaults.headers.common['Accept']= 'application/json';

*Then just import this file No export needed just the file to your root file

Interceptors

Need to learn