feat: add authenticated http factory to create an axios instance with bearer header

This commit is contained in:
kolaente 2022-01-14 21:52:00 +01:00
parent c8558e6b25
commit c67820f98d
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 18 additions and 7 deletions

View File

@ -1,7 +1,22 @@
import axios from 'axios'
import {getToken} from '@/helpers/auth'
export const HTTPFactory = () => {
return axios.create({
baseURL: window.API_URL,
})
}
export const AuthenticatedHTTPFactory = (token = null) => {
if (token === null) {
token = getToken()
}
return axios.create({
baseURL: window.API_URL,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
})
}

View File

@ -1,4 +1,4 @@
import {HTTPFactory} from '@/http-common'
import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common'
import {getCurrentLanguage, saveLanguage} from '@/i18n'
import {LOADING} from '../mutation-types'
import UserModel from '@/models/user'
@ -211,13 +211,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