Created
June 4, 2020 10:58
-
-
Save robypez/6b2daa526a7bec785597821ebacaa8d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
const API_URL = 'http://localhost:3000' | |
const securedAxiosInstance = axios.create({ | |
baseURL: API_URL, | |
withCredentials: true, | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}) | |
const plainAxiosInstance = axios.create({ | |
baseURL: API_URL, | |
withCredentials: true, | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}) | |
securedAxiosInstance.interceptors.request.use(config => { | |
const method = config.method.toUpperCase() | |
if (method !== 'OPTIONS' && method !== 'GET') { | |
config.headers = { | |
...config.headers, | |
'X-CSRF-TOKEN': localStorage.csrf | |
} | |
} | |
return config | |
}) | |
securedAxiosInstance.interceptors.response.use(null, error => { | |
if (error.response && error.response.config && error.response.status === 401) { | |
// In case 401 is caused by expired access cookie - we'll do refresh request | |
return plainAxiosInstance.post('/refresh', {}, { headers: { 'X-CSRF-TOKEN': localStorage.csrf } }) | |
.then(response => { | |
localStorage.csrf = response.data.csrf | |
localStorage.signedIn = true | |
// And after successful refresh - repeat the original request | |
let retryConfig = error.response.config | |
retryConfig.headers['X-CSRF-TOKEN'] = localStorage.csrf | |
return plainAxiosInstance.request(retryConfig) | |
}).catch(error => { | |
delete localStorage.csrf | |
delete localStorage.signedIn | |
// redirect to signin in case refresh request fails | |
location.replace('/') | |
return Promise.reject(error) | |
}) | |
} else { | |
return Promise.reject(error) | |
} | |
}) | |
export { securedAxiosInstance, plainAxiosInstance } | |
// todos-vue/src/main.js | |
import Vue from 'vue' | |
import App from './App' | |
import router from './router' | |
import VueAxios from 'vue-axios' | |
import { securedAxiosInstance, plainAxiosInstance } from './backend/axios' | |
Vue.config.productionTip = false | |
Vue.use(VueAxios, { | |
secured: securedAxiosInstance, | |
plain: plainAxiosInstance | |
}) | |
/* eslint-disable no-new */ | |
new Vue({ | |
el: '#app', | |
router, | |
securedAxiosInstance, | |
plainAxiosInstance, | |
components: { App }, | |
template: '<App/>' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment