Axios: Intercept 401 and logut (session expired or revoked)
This commit is contained in:
parent
bdcf9668b7
commit
5c11e02b2c
|
@ -1,4 +1,4 @@
|
||||||
import axios, { AxiosInstance } from 'axios';
|
import axios, { AxiosInstance, AxiosError } from 'axios';
|
||||||
import { boot } from 'quasar/wrappers';
|
import { boot } from 'quasar/wrappers';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { Store } from 'vuex';
|
import { Store } from 'vuex';
|
||||||
|
@ -15,6 +15,9 @@ export default boot<Store<StateInterface>>(({ Vue, store }) => {
|
||||||
Vue.prototype.$axios = axios;
|
Vue.prototype.$axios = axios;
|
||||||
axios.defaults.baseURL = config.baseURL;
|
axios.defaults.baseURL = config.baseURL;
|
||||||
|
|
||||||
|
/***
|
||||||
|
* Intercept requests and insert Token if available
|
||||||
|
*/
|
||||||
axios.interceptors.request.use(config => {
|
axios.interceptors.request.use(config => {
|
||||||
const session = store.state.session.currentSession;
|
const session = store.state.session.currentSession;
|
||||||
if (session?.token) {
|
if (session?.token) {
|
||||||
|
@ -22,6 +25,22 @@ export default boot<Store<StateInterface>>(({ Vue, store }) => {
|
||||||
}
|
}
|
||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/***
|
||||||
|
* Intercept responses, filter 401 and logout
|
||||||
|
*/
|
||||||
|
axios.interceptors.response.use(
|
||||||
|
response => response,
|
||||||
|
error => {
|
||||||
|
if (error && 'response' in error) {
|
||||||
|
const e = <AxiosError>error;
|
||||||
|
if (e.response && e.response.status == 401) {
|
||||||
|
return store.dispatch('session/clearup');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
export { axios };
|
export { axios };
|
||||||
|
|
Loading…
Reference in New Issue