DEV Community

Ahmet Eren Yatkın
Ahmet Eren Yatkın

Posted on

Creating HTTP Client Instance with Axios in Vue

I was assigned to a new project at my office and we chose Vue, Symfony, Postgres tech stack to develop the application.

 The Problem

The app is separated into frontend and backend, so it will heavily make API calls. How can I create an instance to prevent me from writing the same lines of code over and over again? How I can improve the readability of the code? These are the problems I need to solve.

The Goal

My aim is to create an instance to manage all HTTP requests - responses and headers - easily.

The Prerequisites

These are the tools we need;

  • VS Code Or any other text editor
  • Terminal
  • NodeJS
  • VueJS
  • Axios

The Solution

We are ready now! We can start coding. First, we will install Vue-CLI.

npm install -g @vue/cli

We will now create our Vue project via the command line tool. I chose default settings, feel free to configure.

vue create test-proj
-----------------------------------------------
🎉  Successfully created project test-proj.
👉  Get started with the following commands:
 $ cd test-proj
 $ npm run serve

After that, head to the project's root folder and install the mighty Axios package.

npm install axios --save
----------------------
+ axios@0.18.0
added 1 package from 1 contributor and audited 23811 packages in 12.657s
found 0 vulnerabilities

Next step is to create a layer for the instance, I named the layer "Service" and I add a js file into it.

-test-proj
--src
---service
----index.js

We need to import Axios, also I exported an empty arrow function.

import axios from 'axios';


export default () => {};

Now, we can create our Axios instance. At first, I will just define our server URL. So every request will use this base URL and connect the URL extension we will give.

import axios from 'axios';

export default () => {
  const options = {};
  options.baseURL = 'http://localhost:3000/api/';
  const instance = axios.create(options);
  return instance;
};

Our backend uses the JWT protocol to secure the routes. So we need to define the Authorization header. I edit the index.js like below. Passed an object as a parameter with a default value and added Authorization property to headers. Axios will include JWT token to requests if we pass true.

import axios from 'axios';

export default ({ requiresAuth = false } = {}) => {
  const options = {};
  options.baseURL = 'http://localhost:3000';

  //? Decide add token or not
  if (requiresAuth) {
    options.headers.Authorization = 'JWT TOKEN'
  }
  const instance = axios.create(options);
  return instance;
};

Well, we created our service instance, how do we use it? It's so simple:

import service from './index';

export default {
  dummyData() {
    return service({ requiresAtuh: true }).get('dummyData');
  }
};

Okay, let's go back to the instance; what more can we do? Actually it is limited to our imagination but let me add one more thing. We can interfere with every request-response before it executes.

import axios from 'axios';

export default ({ requiresAuth = false } = {}) => {
  const options = {};
  options.baseURL = 'http://localhost:3000';

  if (requiresAuth) {
    options.headers.Authorization = 'JWT TOKEN'
  }
  const instance = axios.create(options);

  instance.interceptors.response.use(response => {
    console.log('good boi!');
    return response;
  }, error => {
    return Promise.reject(error);
  });
  return instance;
};

I just added interceptors.response.use . First callback handles if the request is successful and second callback handles if the request fails. Also do not forget to return response and error otherwise function we call will not return response or error.

The End

So we've reach the end and have created an instance for ourselves which is easily manageable.
With this approach, our Http Requests will have the same options and headers, and therefore we will not have to re-write the same code over and over again.
Also, we could easily alter the requests and the responses for each call we will make. See you all in the next article, have a nice productive day!

Ahmet Eren Yatkın

Top comments (0)