Skip to content

Instantly share code, notes, and snippets.

@NathanWailes
Created April 4, 2022 17:53
Show Gist options
  • Save NathanWailes/6fcf962776ecce9d6422ed760a7b848b to your computer and use it in GitHub Desktop.
Save NathanWailes/6fcf962776ecce9d6422ed760a7b848b to your computer and use it in GitHub Desktop.
import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';
import userConfig from '../../user.config.json'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$axios: AxiosInstance;
$api: AxiosInstance;
}
}
const api = axios.create({
baseURL: process.env.VUE_APP_BACKEND_BASE_URL ? process.env.VUE_APP_BACKEND_BASE_URL + '/api/v1/' : '/api/v1/',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
})
api.interceptors.request.use(function (config) {
// Add the saved GitHub access token to the request if the user has one; this is how the back-end will know the user
// is authenticated (assuming both the access token and the refresh token haven't expired yet).
const accessToken = window.localStorage.getItem('access_token')
if (accessToken) {
config.headers.Authorization = 'token ' + accessToken
}
return config
})
export default boot(({ app, router }) => {
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$api = api;
api.interceptors.response.use(function (response) {
if (response.headers.hasOwnProperty('x-updated-access-token')) {
window.localStorage.removeItem('access_token')
window.localStorage.setItem('access_token', response.headers['x-updated-access-token'])
}
return response
}, function (error) {
console.log(error)
if (error.response.status === 401) {
window.localStorage.removeItem('access_token')
void router.push('login')
}
return Promise.reject(error)
})
})
export { api }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment