55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { boot } from 'quasar/wrappers';
|
||
import axios, { AxiosInstance } from 'axios';
|
||
import {router} from 'src/router';
|
||
|
||
declare module '@vue/runtime-core' {
|
||
interface ComponentCustomProperties {
|
||
$axios: AxiosInstance;
|
||
$api: AxiosInstance;
|
||
}
|
||
}
|
||
|
||
// Be careful when using SSR for cross-request state pollution
|
||
// due to creating a Singleton instance here;
|
||
// If any client changes this (global) instance, it might be a
|
||
// good idea to move this instance creation inside of the
|
||
// "export default () => {}" function below (which runs individually
|
||
// for each client)
|
||
const api:AxiosInstance = axios.create({ baseURL: process.env.KAB_BACKEND_URL });
|
||
const token=localStorage.getItem('token')||'';
|
||
if(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);
|
||
localStorage.removeItem('token');
|
||
router.replace({
|
||
path:"/login",
|
||
query:{redirect:router.currentRoute.value.fullPath}
|
||
});
|
||
}
|
||
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
|
||
|
||
app.config.globalProperties.$api = api;
|
||
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
|
||
// so you can easily perform requests against your app's API
|
||
app.provide<AxiosInstance>('$api',api);
|
||
app.provide<AxiosInstance>('$axios',axios);
|
||
|
||
});
|
||
|
||
export { api };
|