axiosでトークン取得を修正する

This commit is contained in:
Mouriya
2024-08-08 16:09:45 +09:00
parent 7e6143cac7
commit 5889874720

View File

@@ -1,6 +1,7 @@
import { boot } from 'quasar/wrappers'; import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import {router} from 'src/router'; import {router} from 'src/router';
import { useAuthStore } from 'src/stores/useAuthStore';
declare module '@vue/runtime-core' { declare module '@vue/runtime-core' {
interface ComponentCustomProperties { interface ComponentCustomProperties {
@@ -15,9 +16,10 @@ declare module '@vue/runtime-core' {
// good idea to move this instance creation inside of the // good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually // "export default () => {}" function below (which runs individually
// for each client) // for each client)
const authStore = useAuthStore()
const api:AxiosInstance = axios.create({ baseURL: process.env.KAB_BACKEND_URL }); const api:AxiosInstance = axios.create({ baseURL: process.env.KAB_BACKEND_URL });
const token=JSON.parse(localStorage.getItem('auth') ?? '{}')?.token ?? ''; const token = authStore.token;
if(token!==''){ if(token && token!==''){
api.defaults.headers["Authorization"]='Bearer ' + token; api.defaults.headers["Authorization"]='Bearer ' + token;
} }
//axios例外キャプチャー //axios例外キャプチャー
@@ -27,11 +29,7 @@ api.interceptors.response.use(
if (error.response && error.response.status === 401) { if (error.response && error.response.status === 401) {
// 認証エラーの場合再ログインする // 認証エラーの場合再ログインする
console.error('(; ゚Д゚)/認証エラー(401)', error); console.error('(; ゚Д゚)/認証エラー(401)', error);
localStorage.removeItem('token'); authStore.logout()
router.replace({
path:"/login",
query:{redirect:router.currentRoute.value.fullPath}
});
} }
return Promise.reject(error); return Promise.reject(error);
} }