create axios instance code example

Example 1: header in axios

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)

Example 2: axios get

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Example 3: axios post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Example 4: axios instance

// lets you create custom pre-configured fetch api call!
const getUser = axios.create({
  baseURL: 'https://randomuser.me/api/', // we define url
  timeout: 1000, // (optional) set timeout
  headers: {'X-Custom-Header': 'foobar'} // pass headers
});

// use later like this
getUser().then(response => console.log(response))

Example 5: axios get

import axios from 'axios';

await axios.get('/user', {
    params: {
      ID: 12345
    }
  })

Example 6: axios put

const res = await axios.put('https://httpbin.org/put', { hello: 'world' });

res.data.headers['Content-Type']; // application/json;charset=utf-8