Create HTTP Client Instance With Axios in Vue

Eren Yatkin
Apr 20 · 3 min read
Background vector created by starline — www.freepik.com

Hello folks, this is my first story on Medium. Six years ago back in college days I started blogging but I did not give due consideration to it. Today I decided to take up where I left off and it’s exciting right now. Well let’s talk about what I encounter and how I solve ?

I 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 writing the same codes over and over again ? How I can improve 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 also I am a lazy dev I do not want to write same codes over and over again.

The Prerequisites

These are the tools we need;

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 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 concat 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 JWT protocol to secure the routes. So we need to define Authorization header. I edit the index.js like below. Passed an object as a parameter with 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 can we do more ? Actually it is limited to our imagination but let me add one more thing. We can interfere 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 request is successful and second callback handles if request fails. Also do not forget to return response and error otherwise function we call will not return response or error.

So we reach the end, hopefully you can find something useful. Cya.

Ahmet Eren Yatkın

Eren Yatkin

Written by

Fullstack software developer who wants to share his knowledge across the universe. http://www.erenyatkin.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade