github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/static_source/admin/src/api/api.ts (about) 1 import {Api} from '@/api/stub'; 2 import {useCache} from "@/hooks/web/useCache"; 3 import {ElMessage, ElNotification} from "element-plus"; 4 import {useI18n} from "@/hooks/web/useI18n"; 5 import {useAppStoreWithOut} from "@/store/modules/app"; 6 import {resetRouter} from "@/router"; 7 import {useTagsViewStore} from "@/store/modules/tagsView"; 8 9 const {t} = useI18n() 10 const {wsCache} = useCache() 11 const appStore = useAppStoreWithOut() 12 const tagsViewStore = useTagsViewStore() 13 14 const api = new Api({ 15 baseURL: import.meta.env.VITE_API_BASEPATH as string || '/', // url = base url + request url 16 timeout: 60000 17 // withCredentials: true // send cookies when cross-domain requests 18 }); 19 20 // Request interceptors 21 api.instance.interceptors.request.use( 22 (config) => { 23 // Add X-Access-Token header to every request, you can add other custom headers here 24 if (wsCache.get('accessToken')) { 25 config.headers.Authorization = wsCache.get('accessToken'); 26 } 27 // Add X-SERVER-ID 28 if (wsCache.get('serverId')) { 29 config.headers['X-SERVER-ID'] = wsCache.get('serverId'); 30 } 31 return config; 32 }, 33 (error) => { 34 Promise.reject(error); 35 } 36 ); 37 // Response interceptors 38 api.instance.interceptors.response.use( 39 (response) => { 40 return response; 41 }, 42 (error) => { 43 if (!error.response) { 44 return 45 } 46 const response = error.response 47 const res = response.data; 48 49 if (response.status == 526 ) { 50 ElMessage({ 51 message: 'No proxy available', 52 type: 'error', 53 duration: 5 * 1000 54 }); 55 return 56 } 57 58 if (response.status == 403 ) { 59 ElMessage({ 60 message: 'access forbidden: ' + res.error.message, 61 type: 'error', 62 duration: 5 * 1000 63 }); 64 return 65 } 66 67 ElMessage({ 68 message: res.error.message || t('Error'), 69 type: 'error', 70 duration: 5 * 1000 71 }); 72 73 if (response.status === 401 ) { 74 75 if (location.toString().includes('/login') || location.toString().includes('/password_reset') || 76 location.toString().includes('/landing')) { 77 return 78 } 79 80 appStore.RemoveToken() 81 //wsCache.clear() 82 83 tagsViewStore.delAllViews() 84 resetRouter() // 重置静态路由表 85 location.reload() // To prevent bugs from vue-router 86 return 87 } 88 89 if (res.details) { 90 for (const i in res.details) { 91 ElNotification({ 92 message: res.details[i].description || t('message.unknownError'), 93 title: t('Warning'), 94 type: 'warning', 95 showClose: true, 96 duration: 5 * 1000, 97 }); 98 } 99 } 100 101 return Promise.reject(error); 102 } 103 ); 104 105 export default api;