From 5c11e02b2c4739507e6e90006b3217b91fdf004a Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Fri, 6 Nov 2020 01:15:40 +0100 Subject: [PATCH] Axios: Intercept 401 and logut (session expired or revoked) --- src/boot/axios.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/boot/axios.ts b/src/boot/axios.ts index b6255dc..4de466e 100644 --- a/src/boot/axios.ts +++ b/src/boot/axios.ts @@ -1,4 +1,4 @@ -import axios, { AxiosInstance } from 'axios'; +import axios, { AxiosInstance, AxiosError } from 'axios'; import { boot } from 'quasar/wrappers'; import config from '../config'; import { Store } from 'vuex'; @@ -15,6 +15,9 @@ export default boot>(({ Vue, store }) => { Vue.prototype.$axios = axios; axios.defaults.baseURL = config.baseURL; + /*** + * Intercept requests and insert Token if available + */ axios.interceptors.request.use(config => { const session = store.state.session.currentSession; if (session?.token) { @@ -22,6 +25,22 @@ export default boot>(({ Vue, store }) => { } return config; }); + + /*** + * Intercept responses, filter 401 and logout + */ + axios.interceptors.response.use( + response => response, + error => { + if (error && 'response' in error) { + const e = error; + if (e.response && e.response.status == 401) { + return store.dispatch('session/clearup'); + } + } + return Promise.reject(error); + } + ); }); export { axios };