From 1728006c7507dc973e684e0b03040304fa05e08a Mon Sep 17 00:00:00 2001
From: GuLiMmo <2820890765@qq.com>
Date: Tue, 27 Aug 2024 17:03:32 +0800
Subject: [PATCH] chore:接入新框架api
---
src/api/http/request.ts | 166 ++++++++++++++++++++++++++++++++++++++++++++++++-------
1 files changed, 145 insertions(+), 21 deletions(-)
diff --git a/src/api/http/request.ts b/src/api/http/request.ts
index b66b2a9..b7e6fec 100644
--- a/src/api/http/request.ts
+++ b/src/api/http/request.ts
@@ -1,56 +1,180 @@
+/*
+ * @Author: GuLiMmo 2820890765@qq.com
+ * @Date: 2024-03-12 18:01:28
+ * @LastEditors: GuLiMmo 2820890765@qq.com
+ * @LastEditTime: 2024-08-27 16:16:55
+ * @FilePath: /drone-web/src/api/http/request.ts
+ * @Description: axios配置
+ * Copyright (c) 2024 by GuLiMmo, All Rights Reserved.
+ */
-import axios from 'axios'
+import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { uuidv4 } from '/@/utils/uuid'
import { CURRENT_CONFIG } from './config'
-import { message } from 'ant-design-vue'
+import { useMyStore } 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'
-const { baseUrl: { apiBaseUrl } } = window.globalApiConfig
+// 自定义响应类型
+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)
}
-const instance = axios.create({
+const instance: CustomAxiosConfig = axios.create({
// withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
- baseURL: apiBaseUrl || import.meta.env.VITE_BASE_API,
+ 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: {
+ 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-yw' + 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 statusWhiteList = website.statusWhiteList || []
+ const message = res.data.msg || res.data.message || res.data.error_description || '未知错误'
+ // 如果在白名单里则自行catch逻辑处理
+ if ((statusWhiteList as any).includes(status)) return Promise.reject(res)
+ // 洪水预警接口地址放开
+ const hsyjWhiteList = [
+ '/fh-admin/skkr/getFuture',
+ 'https://sk.hubeishuiyi.cn/hsybApi/api/fh-admin/skkr/getFuture',
+ '/hsybApi/api/fh-admin/skkr/getFuture',
+ ]
+ if (hsyjWhiteList.includes(res.config.url)) return Promise.resolve(res)
+ // 如果是401则跳转到登录页面
+ const store = useMyStore()
+ if (status === 401) store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))
+ // 如果请求为非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)
@@ -66,11 +190,11 @@
}
// @See: https://github.com/axios/axios/issues/383
if (!err.response || !err.response.status) {
- message.error('网络异常,请检查后端服务后重试')
+ Message.error('网络异常,请检查后端服务后重试')
return
}
if (err.response?.status !== 200) {
- message.error(`错误码: ${err.response?.status}`)
+ Message.error(`错误码: ${err.response?.status}`)
}
// if (err.response?.status === 403) {
// // window.location.href = '/'
--
Gitblit v1.9.3