Explorar o código

feat(utils): 添加请求工具模块并优化路由处理

- 新增 request.ts 文件,实现 AxiosInstance 的封装和自定义请求方法
- 添加对错误响应的统一处理和提示
- 更新路由处理逻辑,支持隐藏和禁用路由项
- 在 vite.config.ts 中添加开发服务器代理配置
nahida hai 11 meses
pai
achega
91b17bc5b6
Modificáronse 3 ficheiros con 115 adicións e 9 borrados
  1. 36 9
      src/router/route.ts
  2. 70 0
      src/utils/request.ts
  3. 9 0
      vite.config.ts

+ 36 - 9
src/router/route.ts

@@ -3,21 +3,30 @@ export interface RouterType {
   name:string,
   addr?:string,
   icon?:string,
+  meta?: { hide?: boolean, disable?: boolean },
   children?:RouterType[]
 }
 
-export const buildTree =(routes: RouterType[]): RouterType[]=> {
+export const buildTree = (routes: RouterType[]): RouterType[] => {
+  // 先过滤掉需要隐藏的路由项
+  const filteredRoutes = routes.filter(route => !route.meta?.hide)
+
   const map: { [key: string]: RouterType } = {}
   const tree: RouterType[] = []
-  routes.forEach(route => {
+
+  // 初始化 map
+  filteredRoutes.forEach(route => {
     map[route.path] = { ...route, children: [] }
   })
 
-  for (const route of routes) {
+  // 构建父子关系
+  for (const route of filteredRoutes) {
     const parentPath = route.path.substring(0, route.path.lastIndexOf('/'))
     if (map[parentPath]) {
-      map[parentPath].children?.push(map[route.path])
+      // 如果父节点存在,则将当前节点加入其子节点数组
+      map[parentPath].children!.push(map[route.path])
     } else {
+      // 否则作为根节点加入树中
       tree.push(map[route.path])
     }
   }
@@ -36,14 +45,32 @@ export const routeList:RouterType[] = [
     path: 'ar/edit',
     name: '编辑页面',
     icon: 'Location',
-    addr: 'ar/edit'
+    addr: 'ar/edit',
+    meta: { hide: false,disable:false }
+  },
+  {
+    path: 'ar/room',
+    name: '房间',
+    icon: 'Location',
+    addr: 'ar/room',
+    meta: { hide: true }
+  },
+  {
+    path: 'ar/preview',
+    name: '预览页面',
+    icon: 'Location',
+    addr: 'ar/preview',
+    meta: { hide: false,disable:false }
   },
 ]
 export const useDynamicRoutes: () => RouterType[] = () => {
-  routeList.forEach(item => {
+  // 过滤掉 meta.disable === true 的路由
+  const filteredList = routeList.filter(item => !item.meta?.disable)
+
+  // 设置组件地址
+  filteredList.forEach(item => {
     item.addr = `views/${item.addr}.vue`
   })
-  return [
-    ...routeList
-  ]
+
+  return [...filteredList]
 }

+ 70 - 0
src/utils/request.ts

@@ -0,0 +1,70 @@
+import axios, {
+  type AxiosError,
+  type AxiosInstance,
+  type AxiosRequestConfig,
+  type AxiosResponse,
+  type InternalAxiosRequestConfig
+} from 'axios'
+import { ElMessage } from 'element-plus'; // 导入 Element Plus 的 ElMessage 组件
+
+const instance: AxiosInstance = axios.create({
+  baseURL: import.meta.env.VITE_APP_BASE_API, // 从环境变量中获取基础 URL
+  timeout: 10000, // 请求超时时间
+  headers: {
+    'Content-Type': 'application/json',
+  },
+});
+
+instance.interceptors.request.use(
+  (config: InternalAxiosRequestConfig) => {
+    // 可以在这里添加通用的请求头
+    return config;
+  },
+  (error:AxiosError) => {
+    return Promise.reject(error);
+  }
+);
+
+// 响应拦截器
+instance.interceptors.response.use(
+  (response: AxiosResponse) => {
+    return response.data; // 返回响应数据
+  },
+  (error:AxiosError) => {
+    // 处理错误
+    if (error.response) {
+      // 服务器返回了错误状态码
+      const { status, data } = error.response;
+      ElMessage.error(`请求失败,状态码: ${status},错误信息: ${data}`);
+      return Promise.reject(data);
+    } else if (error.request) {
+      // 请求已发出,但没有收到响应
+      ElMessage.error('请求已发出,但没有收到响应');
+      return Promise.reject({ message: 'No response received' });
+    } else {
+      // 发生了其他错误
+      ElMessage.error(`发生错误: ${error.message}`);
+      return Promise.reject({ message: error.message });
+    }
+  }
+);
+export const clientGet = <T, R>(url: string, config?: AxiosRequestConfig) =>
+  instance.get<T, R>(url, config);
+
+export const clientPost = <T,R>(url: string, data?: T, config?: AxiosRequestConfig) =>
+  instance.post<T,R>(url, data, config);
+
+export const clientPut = <T,R>(url: string, data?: T, config?: AxiosRequestConfig) =>
+  instance.put<T,R>(url, data, config);
+
+export const clientDel = <T,R>(url: string, config?: AxiosRequestConfig) =>
+  instance.delete<T,R>(url, config);
+
+// 新增:专门用于发送 FormData 的 POST 请求
+export const clientPostFormData = <T, R>(url: string, data: T, config?: AxiosRequestConfig): Promise<R> =>
+  instance.post<T, R>(url, data, {
+    ...config,
+    headers: {
+      'Content-Type': 'multipart/form-data', // 明确设置为 multipart/form-data
+    },
+  });

+ 9 - 0
vite.config.ts

@@ -28,4 +28,13 @@ export default defineConfig({
       '@': fileURLToPath(new URL('./src', import.meta.url))
     },
   },
+  server: {
+    proxy: {
+      '/api': {
+        target: 'http://192.168.110.117:8801',
+        changeOrigin: true,
+        rewrite: (path) => path.replace(/^\/api/, '')
+      }
+    }
+  }
 })