69 lines
2.8 KiB
TypeScript
69 lines
2.8 KiB
TypeScript
import type { AxiosError } from 'axios';
|
||
|
||
import { Request } from '@/utils/request';
|
||
import { useUserStore } from '@/stores/user';
|
||
import { getAppEnvConfig } from '@/utils/env';
|
||
|
||
import router from '@/router';
|
||
|
||
export const userClient = new Request({
|
||
requestInterceptor: (config) => {
|
||
const userStore = useUserStore();
|
||
const { lampAuthorization, lampClientId, lampClientSecret } = getAppEnvConfig();
|
||
const newAuthorization = window.btoa(`${lampClientId}:${lampClientSecret}`);
|
||
const authorization = lampAuthorization.trim() !== '' ? lampAuthorization : newAuthorization;
|
||
config.headers.set('accept-language', 'zh-CN,zh;q=0.9');
|
||
config.headers.set('accept', 'application/json, text/plain, */*');
|
||
config.headers.set('Applicationid', '');
|
||
config.headers.set('Tenantid', '1');
|
||
config.headers.set('Authorization', authorization);
|
||
config.headers.set('token', userStore.userLoginResult?.token ?? '');
|
||
return config;
|
||
},
|
||
responseInterceptor: (response) => {
|
||
return response;
|
||
},
|
||
responseErrorInterceptor: (error) => {
|
||
const err = error as AxiosError;
|
||
if (err.response?.status === 401) {
|
||
window.$message.error('登录超时,请重新登录');
|
||
const userStore = useUserStore();
|
||
userStore.resetStore();
|
||
router.push('/login');
|
||
}
|
||
if (err.response?.status === 404) {
|
||
router.push('/404');
|
||
}
|
||
return Promise.reject(error);
|
||
},
|
||
});
|
||
|
||
export const ndmClient = new Request({
|
||
requestInterceptor: async (config) => {
|
||
const userStore = useUserStore();
|
||
const { lampAuthorization, lampClientId, lampClientSecret } = getAppEnvConfig();
|
||
const newAuthorization = window.btoa(`${lampClientId}:${lampClientSecret}`);
|
||
const authorization = lampAuthorization.trim() !== '' ? lampAuthorization : newAuthorization;
|
||
config.headers.set('accept-language', 'zh-CN,zh;q=0.9');
|
||
config.headers.set('accept', 'application/json, text/plain, */*');
|
||
config.headers.set('Applicationid', '');
|
||
config.headers.set('Tenantid', '1');
|
||
config.headers.set('Authorization', authorization);
|
||
const staticCode = config.url?.split('/api').at(0)?.split('/').at(-1) ?? '';
|
||
config.headers.set('token', userStore.lampLoginResultRecord?.[staticCode]?.token ?? '');
|
||
return config;
|
||
},
|
||
responseErrorInterceptor: async (error) => {
|
||
const err = error as AxiosError;
|
||
if (err.response?.status === 401) {
|
||
// 当车站请求由于token时效而失败时,需要重新登录车站获取token,然后重新请求
|
||
const stationCode = err.config?.url?.split('/api').at(0)?.split('/').at(-1) ?? '';
|
||
const userStore = useUserStore();
|
||
await userStore.lampLogin(stationCode);
|
||
error.config.headers.token = userStore.lampLoginResultRecord?.[stationCode]?.token ?? '';
|
||
return ndmClient.requestInstance(error.config);
|
||
}
|
||
return Promise.reject(error);
|
||
},
|
||
});
|