By setting the default baseurl in Axios, we don’t need to call the APIs with whole url. Only the endpoint will be required. The simplest procedure of doing this is by creating a separate component file and setting all default parameters there.

Create a component, axios.js –

import axios from 'axios';
const instance = axios.create({baseURL: 'https://www.example.com'});
export default instance

In this component, we have exported the axios package and created an instance with all default parameters. For this articles, we are concerned with baseURL only. Now we need to import this file throughout our application where we need to make an API call.

So, suppose you need to get JSON from endpoint /superhero/, you will do it like this –

Create a file, superhero.js –

import axios from 'axios/axios.js'
// This axios instance is custom. Imported from our created axios.js file

function SuperHero() {
  const [superHeroJSON, setSuperHeroJSON] = React.useState({});
  React.useEffect(() => {
     axios.get('/superhero/').then(response => {
       setSuperHeroJSON(response);
     }).catch(error => {});

  }, [])

  return (<>
    {JSON.stringify(superHeroJSON, null, '    ')}
  </>)
}

export default SuperHero;

In this example we are using our custom axios component and not the one shipped by Axios package. This component is set with default baseURL of example.com and so we do not need to provide full url in axios.get.

You can also set default headers, request / response parameters while setting up Axios instance.

To set content-type header –

import axios from 'axios';
const instance = axios.create({baseURL: 'https://www.example.com'});
instance.defaults.headers.common['Content-Type'] = 'multipart/form-data';

export default instance

Β Β Β Β Tweet this to help others

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles