From 59da6686d08071db7011bc928dc50c5c3a78553b Mon Sep 17 00:00:00 2001 From: kolaente Date: Fri, 14 Jan 2022 21:52:00 +0100 Subject: [PATCH] feat: add authenticated http factory to create an axios instance with bearer header --- src/http-common/index.js | 13 ++++++++++++- src/store/modules/auth.js | 10 +++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/http-common/index.js b/src/http-common/index.js index 66835fc5..e6c116cd 100644 --- a/src/http-common/index.js +++ b/src/http-common/index.js @@ -1,7 +1,18 @@ import axios from 'axios' +import {getToken} from '@/helpers/auth' -export const HTTPFactory = () => { +export function HTTPFactory() { return axios.create({ baseURL: window.API_URL, }) } + +export function AuthenticatedHTTPFactory(token = getToken()) { + return axios.create({ + baseURL: window.API_URL, + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + }) +} diff --git a/src/store/modules/auth.js b/src/store/modules/auth.js index 9e2f9cbb..99291a2a 100644 --- a/src/store/modules/auth.js +++ b/src/store/modules/auth.js @@ -1,4 +1,4 @@ -import {HTTPFactory} from '@/http-common' +import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common' import {i18n, getCurrentLanguage, saveLanguage} from '@/i18n' import {objectToSnakeCase} from '@/helpers/case' import {LOADING} from '../mutation-types' @@ -215,13 +215,9 @@ export default { return } - const HTTP = HTTPFactory() + const HTTP = AuthenticatedHTTPFactory(jwt) try { - const response = await HTTP.get('user', { - headers: { - Authorization: `Bearer ${jwt}`, - }, - }) + const response = await HTTP.get('user') const info = new UserModel(response.data) info.type = state.info.type info.email = state.info.email