setup axios in vue application

·

4 min read

Axios is a very powerful client to make http requests. In case we want to use axios in our vue application. We need to follow below mention steps.

execute below command in our vue js application. By using this command axios client will be installed in our application

Please refer to YouTube video to understand in a better way:

npm i --save axios

Now it's time to setup default application configuration in axios client like logged in user token, headers pass from the single place in application. Open main.ts file in src folder and made following changes. First step is to import axios client.

import axios from 'axios'

setup application base url

axios.defaults.baseURL = 'yourbaseurl.com'

setup default headers:

axios.defaults.headers = {
  'Authorization': 'Bearer' + ' your token',
  "Content-Type": "application/json",
  };

setup default timeout (in milliseconds) for all the service requests

axios.defaults.timeout = 1000;

setup max response size in byte

axios.defaults.maxContentLength = 1000;

setup max request size in byte

axios.defaults.maxBodyLength = 1000;

setup proxy in case you are behind proxy

axios.defaults.proxy = {
  protocol: 'https',
  host: '127.0.0.1',
  port: 9000,
  auth: {
    username: 'test',
    password: 'test'
  }
};

define service response status. promise will resolve in case service return status as per defined status in our axios configuration otherwise reject

axios.defaults.validateStatus = function (status) {
  return status >= 200 && status < 300;
};

our main.ts file axios configuration will look like as follows:

import axios from 'axios'

axios.defaults.baseURL = 'https://yourbaseurl.com'
axios.defaults.headers = {
  'Authorization': 'Bearer' + ' your token',
  "Content-Type": "application/json",
  };
axios.defaults.withCredentials = true;
axios.defaults.timeout = 1000;
axios.defaults.maxContentLength = 100000;
axios.defaults.maxBodyLength = 100000;
axios.defaults.proxy = {
  protocol: 'https',
  host: '127.0.0.1',
  port: 9000,
  auth: {
    username: 'test',
    password: 'test'
  }
};
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status < 300;
};

now it's time to service call in our application

first step is to import axios client in our component like this:

import axios from "axios";

Now we will call service using axios reference like this

axios
      .get("/users/allusers")
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
        // execute always
      });

We are passing only module url in our service call because we have configured base url in our axios configuration above. These are the steps we need to follow to setup axios client in our vue application