axios response object structure code example

Example 1: axios api post request

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

Example 2: axios response.json

const axios = require('axios');

const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });

res.constructor.name; // 'Object', means `res` is a POJO

// `res.data` contains the parsed response body
res.data; // { args: { answer: 42 }, ... }
res.data instanceof Object; // true

Example 3: axios get status code

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

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))