From f27ca082eb0a839449dd50c49007b58e5ed6946f Mon Sep 17 00:00:00 2001
From: 罗广辉 <guanghui.luo@foxmail.com>
Date: Thu, 19 Jun 2025 19:08:01 +0800
Subject: [PATCH] feat: 服务名修改

---
 src/api/http/request.ts |  180 ++++++++++++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 150 insertions(+), 30 deletions(-)

diff --git a/src/api/http/request.ts b/src/api/http/request.ts
index 5d9c1f6..9c0e2e8 100644
--- a/src/api/http/request.ts
+++ b/src/api/http/request.ts
@@ -1,54 +1,173 @@
-import axios from 'axios'
+/*
+ * @Author: GuLiMmo 2820890765@qq.com
+ * @Date: 2024-03-12 18:01:28
+ * @LastEditors: GuLiMmo 2820890765@qq.com
+ * @LastEditTime: 2024-08-28 15:03:34
+ * @FilePath: /drone-web/src/api/http/request.ts
+ * @Description: axios配置
+ * Copyright (c) 2024 by GuLiMmo, All Rights Reserved.
+ */
+
+import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
 import { uuidv4 } from '/@/utils/uuid'
 import { CURRENT_CONFIG } from './config'
-import { message } from 'ant-design-vue'
+import store from '/@/store/'
+import { getToken } from '/@/utils/auth'
+import { serialize } from '/@/utils/common'
+import { message as Message, MessageArgsProps } from 'ant-design-vue'
 import router from '/@/router'
 import { ELocalStorageKey, ERouterName, EUserType } from '/@/types/enums'
+import { VNodeTypes } from 'vue'
+import website from '/@/config/website'
+import { Base64 } from 'js-base64'
 export * from './type'
 
+// 自定义响应类型
+interface CustomAxiosResponse<T = any> extends AxiosResponse<T> {
+  data: T
+}
+
+// 定义你的请求类型
+interface CustomAxiosRequestConfig extends AxiosRequestConfig {
+  // 是否开启鉴权
+  authorization?: boolean
+}
+
+type CustomAxiosConfig = {
+  [x: string]: any
+  <T = any, R = CustomAxiosResponse<T>, D = CustomAxiosRequestConfig>(config: D): Promise<R>
+}
+
 const REQUEST_ID = 'X-Request-Id'
-function getAuthToken () {
+const getAuthToken = () => {
   return localStorage.getItem(ELocalStorageKey.Token)
 }
-console.log(import.meta.env.VITE_API_URL, 'request.ts')
-const instance = axios.create({
+const instance: CustomAxiosConfig = axios.create({
   // withCredentials: true,
   headers: {
     'Content-Type': 'application/json',
   },
+  baseURL: window?.globalApiConfig?.baseUrl?.apiBaseUrl || import.meta.env.VITE_BASE_API,
   // timeout: 12000,
+  withCredentials: true,
 })
 
 instance.interceptors.request.use(
-  config => {
-    config.headers[ELocalStorageKey.Token] = localStorage.getItem(ELocalStorageKey.Token)
-    config.baseURL = import.meta.env.VITE_API_URL
+  (config: {
+    data: any
+    method: string
+    token: any
+    text: boolean
+    json: boolean
+    meta: {
+      isSerialize: boolean
+      isToken: boolean
+      noCookie: boolean
+    }
+    headers: { [x: string]: string | null }
+    url: string
+    authorization: boolean
+  }) => {
+    if (!config.url.includes('/blade-') && !config.url.includes('https://') && !config.url.includes('http://')) {
+      config.url = '/drone-device-core' + config.url
+    }
+    const authorization = config.authorization === false
+    if (!authorization) {
+      config.headers.Authorization = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
+    }
+    // 让每个请求携带token
+    const meta = config.meta || {}
+    const isToken = meta.isToken === false
+    if (getToken() && !isToken) {
+      config.headers[website.tokenHeader] = 'bearer ' + getToken()
+    }
+    if (meta.noCookie) {
+      delete config.headers.cookie
+    }
+    // headers中配置text请求
+    if (config.text === true) {
+      config.headers['Content-Type'] = 'text/plain'
+    }
+    // headers配置JSON请求
+    if (config.json === true) {
+      config.headers['Content-Type'] = 'application/json'
+    }
+    // 水情预报接口调用
+    if (config.token) {
+      config.headers.Authorization = config.token
+    }
+    // headers中配置serialize为true开启序列化
+    if (config.method === 'post' && meta.isSerialize === true) {
+      config.data = serialize(config.data)
+    }
+    // config.headers[ELocalStorageKey.Token] = localStorage.getItem(ELocalStorageKey.Token)
     // config.headers[REQUEST_ID] = uuidv4()
     // config.baseURL = CURRENT_CONFIG.baseURL
     return config
   },
-  error => {
+  (error: any) => {
     return Promise.reject(error)
   },
 )
 
 instance.interceptors.response.use(
-  response => {
-    // console.info('URL: ' + response.config.baseURL + response.config.url, '\nData: ', response.data, '\nResponse:', response)
-    const whiteList = ['/manage/api/v1/live/streams/stop']
-    if (whiteList.includes(response.config.url)) {
-      return Promise.reject(response.data)
+  (res: { data: { code: any; msg: any; message: any; error_description: any }; status: any; config: { url: string; meta: { noCookie: boolean } } }) => {
+    const status = res.data.code || res.status
+    const message = res.data.msg || res.data.message || res.data.error_description || '未知错误'
+    // 如果是401则跳转到登录页面
+    // const store = useMyStore()
+    if (status === 401) {
+      store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))
+      // return
     }
+    // 如果请求为非200否者默认统一处理
+    if (status !== 200) {
+      // 排除海康 code 为 0  情况
+      if (status === 0) {
+        return res
+      }
+      if ('meta' in res.config && 'noCookie' in res.config.meta && res.config.meta.noCookie === true) {
+        return Promise.reject(new Error(message))
+      }
+      if (message === '缺失令牌,鉴权失败') {
+        // message({
+        //   message: '登录信息已过期,请重新登录',
+        //   type: 'warning',
+        // })
+        Message.warning('登录信息已过期,请重新登录')
+      }
+      if (
+        ![
+          '没有收到消息回复。',
+          '未知消息',
+          '设备端退出drc模式',
+          '未能恢复航路作业。错误码:: 319042',
+          'success',
+          '缺失令牌,鉴权失败',
+        ].includes(message)
+      ) {
+        Message.warning(message)
+      }
+      return Promise.reject(new Error(message))
+    }
+    // console.info('URL: ' + response.config.baseURL + response.config.url, '\nData: ', response.data, '\nResponse:', response)
+    // const whiteList = ['/manage/api/v1/live/streams/stop']
+    // if (whiteList.includes(response.config.url)) {
+    //   return Promise.reject(response.data)
+    // }
     // 处理消息返回
     // if (response.data.code && !response.data.success) {
     //   message.error(response.data.message)
     // }
-    if (response.data.code && response.data.code !== 0) {
-      message.error(response.data.message)
-    }
-    return response
+    // if (response.data.code && response.data.code !== 0) {
+    //   message.error(response.data.message)
+    // }
+    return res
   },
-  err => {
+  (err: {
+    config: { headers: { [x: string]: any }; url: any; method: any }
+    response: { data: { message: string; result: { message: string } }; status: number }
+  }) => {
     const requestId = err?.config?.headers && err?.config?.headers[REQUEST_ID]
     if (requestId) {
       console.info(REQUEST_ID, ':', requestId)
@@ -64,26 +183,27 @@
     }
     // @See: https://github.com/axios/axios/issues/383
     if (!err.response || !err.response.status) {
-      message.error('The network is abnormal, please check the backend service and try again')
+      Message.error('网络异常,请检查后端服务后重试')
       return
     }
     if (err.response?.status !== 200) {
-      message.error(`ERROR_CODE: ${err.response?.status}`)
+      Message.error(`错误码: ${err.response?.status}`)
     }
     // if (err.response?.status === 403) {
     //   // window.location.href = '/'
     // }
     if (err.response?.status === 401) {
       console.error(err.response)
-      const flag: number = Number(localStorage.getItem(ELocalStorageKey.Flag))
-      switch (flag) {
-        case EUserType.Web:
-          router.push(ERouterName.PROJECT_LIST)
-          break
-        case EUserType.Pilot:
-          router.push(ERouterName.PILOT)
-          break
-      }
+      store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))
+      // const flag: number = Number(localStorage.getItem(ELocalStorageKey.Flag))
+      // switch (flag) {
+      //   case EUserType.Web:
+      //     router.push(ERouterName.PROJECT_LIST)
+      //     break
+      //   case EUserType.Pilot:
+      //     router.push(ERouterName.PILOT)
+      //     break
+      // }
     }
     return Promise.reject(err)
   },

--
Gitblit v1.9.3