Explorar el Código

进一步优化

chuckchen hace 2 años
padre
commit
f08adecd56
Se han modificado 3 ficheros con 37 adiciones y 116 borrados
  1. 0 61
      src/plugins/VisitAmount.vue
  2. 32 24
      src/utils/request.ts
  3. 5 31
      src/utils/types.ts

+ 0 - 61
src/plugins/VisitAmount.vue

@@ -1,61 +0,0 @@
-<template>
-  <div ref="chartRef" :style="{ height, width }"></div>
-</template>
-<script lang="ts">
-  import { defineComponent, onMounted, ref, Ref } from 'vue';
-  import { useECharts } from '@/hooks/web/useECharts';
-  import { basicProps } from './props';
-
-  export default defineComponent({
-    props: basicProps,
-    setup() {
-      const chartRef = ref<HTMLDivElement | null>(null);
-      const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
-
-      onMounted(() => {
-        setOptions({
-          tooltip: {
-            trigger: 'axis',
-            axisPointer: {
-              lineStyle: {
-                width: 1,
-                color: '#019680',
-              },
-            },
-          },
-          grid: { left: '1%', right: '1%', top: '2  %', bottom: 0, containLabel: true },
-          xAxis: {
-            type: 'category',
-            data: [
-              '1月',
-              '2月',
-              '3月',
-              '4月',
-              '5月',
-              '6月',
-              '7月',
-              '8月',
-              '9月',
-              '10月',
-              '11月',
-              '12月',
-            ],
-          },
-          yAxis: {
-            type: 'value',
-            max: 8000,
-            splitNumber: 4,
-          },
-          series: [
-            {
-              data: [3000, 2000, 3333, 5000, 3200, 4200, 3200, 2100, 3000, 5100, 6000, 3200, 4800],
-              type: 'bar',
-              barMaxWidth: 80,
-            },
-          ],
-        });
-      });
-      return { chartRef };
-    },
-  });
-</script>

+ 32 - 24
src/utils/request.ts

@@ -7,33 +7,23 @@ import { useUserStoreWidthOut } from "@/store/user"
 import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from "axios";
 import { cloneDeep } from 'lodash-es';
 import { Result, RequestOptions, CreateAxiosOptions } from './types';
-import { ResultEnum } from '@/enums/httpEnum';
+import { ResultEnum, ContentTypeEnum } from '@/enums/httpEnum';
+import { useRouter } from 'vue-router';
+
+declare type Recordable<T = any> = Record<string, T>;
+const router = useRouter();
 
 class HttpRequest {
-    private readonly baseURL: string;
-    private readonly withCredentials: boolean;
-    private readonly timeout: number;
 
     private axiosInstance: AxiosInstance;
     private options: CreateAxiosOptions;
 
     constructor(options: CreateAxiosOptions) {
         this.options = options;
-        //获取当前环境的api地址
-        this.baseURL = import.meta.env.VITE_BASE_URL as string;
-        this.withCredentials = true;
-        this.timeout = 1000 * 60;
-        this.axiosInstance = axios.create(this.getInitConfig());
+        console.log(options)
+        this.axiosInstance = axios.create(options);
         this.interceptors(this.axiosInstance);
     }
-    //初始化get请求
-    getInitConfig(): AxiosRequestConfig {
-        return {
-            baseURL: this.baseURL,
-            withCredentials: this.withCredentials,
-            timeout: this.timeout,
-        };
-    }
 
     interceptors(instance: AxiosInstance) {
         // 定义存放请求接口数组
@@ -63,8 +53,13 @@ class HttpRequest {
                 // 请求之前处理config
                 const userStore = useUserStoreWidthOut();
                 const token = userStore.getToken;
-                if (!token) { }
-                config.headers['token'] = token
+                // jwt token
+                if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
+                    // jwt token
+                    (config as Recordable).headers.Authorization = this.options.authenticationScheme
+                      ? `${this.options.authenticationScheme} ${token}`
+                      : token;
+                }
                 return config;
             },
             error => Promise.reject(error + '请求错误')
@@ -73,11 +68,16 @@ class HttpRequest {
         instance.interceptors.response.use(
             response => {
                 setLoadingToFalse(response);
-                if(response.data.code == 'loginTimeout'){ }
+                if(response.data.code === ResultEnum.ERROR){
+                    // 重定向到登录
+                    return router.replace({
+                        path: '/login', query: { redirect: router.currentRoute.value.fullPath }
+                    })
+                }
                 return response.data;
             },
             error => {
-                if (error.response.status == 301) { }
+                if (error.response.status === 301) { }
                 setLoadingToFalse(error);
                 return Promise.reject(error.response?.data);
             }
@@ -85,7 +85,7 @@ class HttpRequest {
     }
 
     /**
-     * @description: 处理请求数据
+     * @description: 处理响应数据
      */
     transformRequestData(res: AxiosResponse<Result>, options: RequestOptions){
         const { data } = res
@@ -131,7 +131,6 @@ class HttpRequest {
                 if (!isCancel) {
                     try {
                         const ret = this.transformRequestData(res, opt);
-                        console.log(res)
                         resolve(ret);
                     } catch (err) {
                         reject(err || new Error('request error!'));
@@ -147,10 +146,19 @@ class HttpRequest {
     }
 }
 const http = new HttpRequest({
+    timeout: 10 * 1000,
+    // jwttoken前缀
+    authenticationScheme: '',
+    baseURL: import.meta.env.VITE_BASE_URL as string,
+    headers: { 'Content-Type': ContentTypeEnum.JSON },
+    // 是否允许跨域携带token
+    withCredentials: false,
     // 配置项,下面的选项都可以在独立的接口请求中覆盖
     requestOptions: {
       // 需要对返回数据进行处理
-      isTransformResponse: true
+      isTransformResponse: true,
+      // 是否需要token
+      withToken: true
     }
   });
 export default http

+ 5 - 31
src/utils/types.ts

@@ -1,39 +1,13 @@
-export interface CreateAxiosOptions {
+import { AxiosRequestConfig } from 'axios';
+
+export interface CreateAxiosOptions extends AxiosRequestConfig {
     requestOptions?: RequestOptions;
+    authenticationScheme?: String;
 }
+
 export interface RequestOptions {
-  // 请求参数拼接到url
-  joinParamsToUrl?: boolean;
-  // 格式化请求参数时间
-  formatDate?: boolean;
-  // 是否显示提示信息
-  isShowMessage?: boolean;
-  // 是否解析成JSON
-  isParseToJson?: boolean;
-  // 成功的文本信息
-  successMessageText?: string;
-  // 是否显示成功信息
-  isShowSuccessMessage?: boolean;
-  // 是否显示失败信息
-  isShowErrorMessage?: boolean;
-  // 错误的文本信息
-  errorMessageText?: string;
-  // 是否加入url
-  joinPrefix?: boolean;
-  // 接口地址, 不填则使用默认apiUrl
-  apiUrl?: string;
-  // 请求拼接路径
-  urlPrefix?: string;
-  // 错误消息提示类型
-  errorMessageMode?: 'none' | 'modal';
-  // 是否添加时间戳
-  joinTime?: boolean;
   // 不进行任何处理,直接返回
   isTransformResponse?: boolean;
-  // 是否返回原生响应头
-  isReturnNativeResponse?: boolean;
-  //忽略重复请求
-  ignoreCancelToken?: boolean;
   // 是否携带token
   withToken?: boolean;
 }