|
@@ -1,7 +1,8 @@
|
|
|
import axios from 'axios';
|
|
|
+import { useUserStore } from '@/stores/modules/userStore';
|
|
|
// import { createDiscreteApi } from 'naive-ui';
|
|
|
|
|
|
-import { tansParams, LocalCache, getQueryParamsAsObject } from "@/utils/tools";
|
|
|
+import { tansParams } from "@/utils/tools";
|
|
|
|
|
|
import type { Result } from '@/types/data';
|
|
|
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios';
|
|
@@ -10,11 +11,13 @@ import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosReq
|
|
|
|
|
|
// const { notification } = createDiscreteApi(["notification"]);
|
|
|
|
|
|
-const CACHE_KEY = 'userInfo';
|
|
|
+const useStore = useUserStore();
|
|
|
+
|
|
|
const url = import.meta.env.VITE_BASE_URL;
|
|
|
const prefix = import.meta.env.VITE_BASE_PREFIX;
|
|
|
const baseURL = url + prefix;
|
|
|
|
|
|
+
|
|
|
enum errorCode {
|
|
|
'请求错误' = 400,
|
|
|
'未授权,请重新登录' = 401,
|
|
@@ -48,17 +51,16 @@ export class Request {
|
|
|
this.instance = axios.create({ ...this.baseConfig, ...config });
|
|
|
|
|
|
this.instance.interceptors.request.use((config: InternalAxiosRequestConfig<Result>) => {
|
|
|
+ const { token } = useStore.userInfo;
|
|
|
+
|
|
|
if (config.method === "get" && config.params) {
|
|
|
let url = config.url + '?' + tansParams(config.params);
|
|
|
url = url.slice(0, -1);
|
|
|
config.params = {};
|
|
|
config.url = url;
|
|
|
}
|
|
|
- const urlParams = getQueryParamsAsObject();
|
|
|
-
|
|
|
- const userInfo = LocalCache.getCache(CACHE_KEY);
|
|
|
-
|
|
|
- config.headers.Authorization = urlParams.token || userInfo?.token ;
|
|
|
+
|
|
|
+ token && (config.headers.Authorization = 'Bearer ' + token);
|
|
|
|
|
|
return config;
|
|
|
}, (err: any) => {
|
|
@@ -66,12 +68,14 @@ export class Request {
|
|
|
});
|
|
|
|
|
|
this.instance.interceptors.response.use(res => {
|
|
|
- const { success, message } = res.data;
|
|
|
+ console.log("res", res);
|
|
|
+ const { code } = res.data;
|
|
|
// !success && showNotification("error", message);
|
|
|
- return success ? res.data : Promise.reject(res);
|
|
|
+ return code === 200 ? res.data : Promise.reject(res.data);
|
|
|
}, (error: AxiosError) => {
|
|
|
const errorMessage = errorCode[error.response?.status as number] || '未知错误';
|
|
|
// showNotification("error", errorMessage);
|
|
|
+ console.log("error", error);
|
|
|
return error;
|
|
|
})
|
|
|
}
|