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

This commit is contained in:
Mouriya
2024-08-08 16:45:44 +09:00
parent 5889874720
commit d9b3f57191
2 changed files with 21 additions and 25 deletions

View File

@@ -1,7 +1,7 @@
import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';
import {router} from 'src/router';
import { useAuthStore } from 'src/stores/useAuthStore';
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
@@ -16,27 +16,10 @@ declare module '@vue/runtime-core' {
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const authStore = useAuthStore()
const api:AxiosInstance = axios.create({ baseURL: process.env.KAB_BACKEND_URL });
const token = authStore.token;
if(token && token!==''){
api.defaults.headers["Authorization"]='Bearer ' + token;
}
//axios例外キャプチャー
api.interceptors.response.use(
(response)=>response,
(error)=>{
if (error.response && error.response.status === 401) {
// 認証エラーの場合再ログインする
console.error('(; ゚Д゚)/認証エラー(401)', error);
authStore.logout()
}
return Promise.reject(error);
}
)
export default boot(({ app }) => {
// for use inside Vue files (Options API) through this.$axios and this.$api
app.config.globalProperties.$axios = axios;
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
// so you won't necessarily have to import axios in each vue file