Calling Axios as a Function

Jan 28, 2021

To use axios in any of your projects you must first import it by assigning it to a variable, which is usually called axios, though you are free to name it anything else.

const axios = require('axios');
typeof axios; // 'function'

Once that is done you can make different requests like axios.get() or axios.post() as needed. However, you can also make an axios() function call. The most barebones axios function call you could make is axios('https://httpbin.org/get') as the default for an axios() function call is the GET request.

Think of the axios() function call similarly to a fetch request where you have to define what kind of request it is and what you want to send in the call as follows:

let res = await axios({
  method: 'GET',
  url: 'https://httpbin.org/get',
  headers:{
    Accept: 'application/json',
  }
});

/*
 * {
 *   args: {},
 *   headers: {
 *     Accept: 'application/json',
 *     Host: 'httpbin.org',
 *     'User-Agent': 'axios/0.19.2',
 *     'X-Amzn-Trace-Id': 'Root=1-6012eaed-26d1f5e15f3bbc4717e33844'
 *   },
 *   origin: '138.207.148.170',
 *   url: 'https://httpbin.org/get'
 * }
 */
res.data;

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!
×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!