Files
admin-sjzx/src/utils/request.ts

319 lines
11 KiB
TypeScript
Raw Normal View History

2024-02-19 13:44:32 +08:00
import type { AxiosRequestConfig, Method } from 'axios'
import axios from 'axios'
import { ElLoading, ElNotification, type LoadingOptions } from 'element-plus'
import { refreshToken } from '@/api/user-boot/user'
import router from '@/router/index'
import { useAdminInfo } from '@/stores/adminInfo'
window.requests = []
window.tokenRefreshing = false
const pendingMap = new Map()
const loadingInstance: LoadingInstance = {
target: null,
count: 0
}
2025-07-21 08:33:33 +08:00
const VITE_FLAG = import.meta.env.VITE_NAME == 'removeMode'
// console.log('🚀 ~ import.meta.env.VITE_NAME:', import.meta.env.VITE_NAME)
2024-02-19 13:44:32 +08:00
/**
* URL
*/
export const getUrl = (): string => {
return '/api'
}
2025-07-21 08:33:33 +08:00
function removeBeforeSecondSlash(str: string) {
// 找到第一个斜杠的位置
const firstSlashIndex = str.indexOf('/')
if (firstSlashIndex === -1) {
// 如果没有斜杠,返回原字符串
return str
}
// 从第一个斜杠之后开始找第二个斜杠
const secondSlashIndex = str.indexOf('/', firstSlashIndex + 1)
if (secondSlashIndex === -1) {
// 如果只有一个斜杠,返回原字符串
return str
}
// 返回第二个斜杠及之后的内容
return str.substring(secondSlashIndex)
}
2024-02-19 13:44:32 +08:00
/**
* `Axios`
* `reductDataFormat(简洁响应)`,`ApiPromise`
* `reductDataFormat`,`AxiosPromise`
*/
function createAxios<Data = any, T = ApiPromise<Data>>(
axiosConfig: AxiosRequestConfig,
options: Options = {},
loading: LoadingOptions = {}
): T {
const adminInfo = useAdminInfo()
const Axios = axios.create({
baseURL: getUrl(),
timeout: 1000 * 60 * 5,
headers: {},
responseType: 'json'
})
options = Object.assign(
{
CancelDuplicateRequest: true, // 是否开启取消重复请求, 默认为 true
loading: false, // 是否开启loading层效果, 默认为false
reductDataFormat: true, // 是否开启简洁的数据结构响应, 默认为true
showErrorMessage: true, // 是否开启接口错误信息展示,默认为true
showCodeMessage: true, // 是否开启code不为1时的信息提示, 默认为true
showSuccessMessage: false, // 是否开启code为1时的信息提示, 默认为false
anotherToken: '' // 当前请求使用另外的用户token
},
options
)
// 请求拦截
Axios.interceptors.request.use(
2025-07-21 08:33:33 +08:00
async (config: any) => {
//嵌入去除所有请求头
if (VITE_FLAG) {
config.url = await removeBeforeSecondSlash(config.url)
}
2024-03-06 16:14:09 +08:00
// 取消重复请求
2024-05-14 18:17:53 +08:00
if (
!(
config.url == '/system-boot/file/upload' ||
config.url == '/harmonic-boot/grid/getAssessOverview' ||
2024-07-18 14:25:53 +08:00
config.url == '/system-boot/file/getFileVO' ||
config.url == '/harmonic-boot/gridDiagram/getGridDiagramAreaData'
)
)
removePending(config)
2024-05-14 18:17:53 +08:00
2024-02-19 13:44:32 +08:00
options.CancelDuplicateRequest && addPending(config)
// 创建loading实例
if (options.loading) {
loadingInstance.count++
if (loadingInstance.count === 1) {
loadingInstance.target = ElLoading.service(loading)
}
}
// 自动携带token
if (config.headers) {
const token = adminInfo.getToken()
if (token) {
;(config.headers as anyObj).Authorization = token
} else {
config.headers.Authorization = 'Basic bmpjbnRlc3Q6bmpjbnBxcw=='
}
}
2024-12-18 11:31:33 +08:00
if (config.url == '/user-boot/user/generateSm2Key' || config.url == '/pqs-auth/oauth/token') {
config.headers.Authorization = 'Basic bmpjbnRlc3Q6bmpjbnBxcw=='
}
2024-03-06 20:37:36 +08:00
2024-02-19 13:44:32 +08:00
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截
Axios.interceptors.response.use(
response => {
removePending(response.config)
options.loading && closeLoading(options) // 关闭loading
2024-02-19 13:44:32 +08:00
if (
response.data.code === 'A0000' ||
response.data.type === 'application/json' ||
Array.isArray(response.data) ||
response.data.size ||
2024-08-29 15:58:30 +08:00
response.config.url == '/harmonic-boot/exportmodel/exportModelJB' ||
2024-09-18 15:52:50 +08:00
response.config.url == '/system-boot/file/download' ||
2024-08-29 15:58:30 +08:00
response.config.url == '/harmonic-boot/powerStatistics/exportExcelListTemplate' ||
response.config.url == '/harmonic-boot/powerStatistics/exportExcelRangTemplate'
2024-04-09 16:52:11 +08:00
// ||
// response.data.type === 'application/octet-stream' ||
// response.data.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
2024-02-19 13:44:32 +08:00
) {
return options.reductDataFormat ? response.data : response
} else if (response.data.code == 'A0202') {
if (!window.tokenRefreshing) {
window.tokenRefreshing = true
2024-12-18 11:31:33 +08:00
2024-02-19 13:44:32 +08:00
return refreshToken()
.then(res => {
2024-12-18 11:31:33 +08:00
adminInfo.setToken(res.data.access_token, 'auth')
window.requests.forEach(cb => cb(res.data.access_token))
2024-02-19 13:44:32 +08:00
window.requests = []
2024-12-18 11:31:33 +08:00
2024-02-19 13:44:32 +08:00
return Axios(response.config)
})
.catch(err => {
adminInfo.removeToken()
router.push({ name: 'login' })
return Promise.reject(err)
})
.finally(() => {
window.tokenRefreshing = false
})
} else {
return new Promise(resolve => {
// 用函数形式将 resolve 存入,等待刷新后再执行
window.requests.push((token: string) => {
response.headers.Authorization = `${token}`
resolve(Axios(response.config))
})
})
}
2025-07-21 08:33:33 +08:00
} else if (response.data.code == 'A0024' || response.data.code == 'null') {
2024-06-04 16:56:57 +08:00
// // 登录失效
2024-12-18 11:31:33 +08:00
ElNotification({
type: 'error',
message: response.data.message
})
2024-02-19 13:44:32 +08:00
adminInfo.removeToken()
router.push({ name: 'login' })
return Promise.reject(response.data)
} else {
if (options.showCodeMessage) {
ElNotification({
type: 'error',
message: response.data.message || '未知错误'
})
}
return Promise.reject(response.data)
}
},
error => {
error.config && removePending(error.config)
options.loading && closeLoading(options) // 关闭loading
return Promise.reject(error) // 错误继续返回给到具体页面
}
)
return Axios(axiosConfig) as T
}
export default createAxios
/**
* Loading层实例
*/
function closeLoading(options: Options) {
if (options.loading && loadingInstance.count > 0) loadingInstance.count--
if (loadingInstance.count === 0) {
loadingInstance.target.close()
loadingInstance.target = null
}
}
/**
* cancel回调,
*/
function addPending(config: AxiosRequestConfig) {
const pendingKey = getPendingKey(config)
config.cancelToken =
config.cancelToken ||
new axios.CancelToken(cancel => {
if (!pendingMap.has(pendingKey)) {
pendingMap.set(pendingKey, cancel)
}
})
}
/**
*
*/
function removePending(config: AxiosRequestConfig) {
const pendingKey = getPendingKey(config)
if (pendingMap.has(pendingKey)) {
const cancelToken = pendingMap.get(pendingKey)
cancelToken(pendingKey)
pendingMap.delete(pendingKey)
}
}
/**
* key
*/
function getPendingKey(config: AxiosRequestConfig) {
let { data } = config
const { url, method, params, headers } = config
if (typeof data === 'string') data = JSON.parse(data) // response里面返回的config.data是个字符串对象
return [
url,
method,
headers && (headers as anyObj).Authorization ? (headers as anyObj).Authorization : '',
headers && (headers as anyObj)['ba-user-token'] ? (headers as anyObj)['ba-user-token'] : '',
JSON.stringify(params),
JSON.stringify(data)
].join('&')
}
/**
* /
*/
2024-08-01 13:58:32 +08:00
export function requestPayload(method: Method, data: anyObj, paramsPOST: boolean) {
2024-02-19 13:44:32 +08:00
if (method == 'GET') {
return {
params: data
}
} else if (method == 'POST') {
2024-08-01 13:58:32 +08:00
if (paramsPOST) {
return { params: data }
} else {
return { data: data }
2024-02-19 13:44:32 +08:00
}
}
}
2024-05-08 20:44:33 +08:00
// 适配器, 用于适配不同的请求方式
export function baseRequest(url, value = {}, method = 'post', options = {}) {
url = sysConfig.API_URL + url
if (method === 'post') {
return service.post(url, value, options)
} else if (method === 'get') {
return service.get(url, { params: value, ...options })
} else if (method === 'formdata') {
// form-data表单提交的方式
return service.post(url, qs.stringify(value), {
headers: {
'Content-Type': 'multipart/form-data'
},
...options
})
} else {
// 其他请求方式例如put、delete
return service({
method: method,
url: url,
data: value,
...options
})
}
}
// 模块内的请求, 会自动加上模块的前缀
export const moduleRequest =
2024-05-14 18:17:53 +08:00
moduleUrl =>
(url, ...arg) => {
return baseRequest(moduleUrl + url, ...arg)
}
2024-02-19 13:44:32 +08:00
interface LoadingInstance {
target: any
count: number
}
interface Options {
// 是否开启取消重复请求, 默认为 true
CancelDuplicateRequest?: boolean
// 是否开启loading层效果, 默认为false
loading?: boolean
// 是否开启简洁的数据结构响应, 默认为true
reductDataFormat?: boolean
// 是否开启code不为A0000时的信息提示, 默认为true
showCodeMessage?: boolean
// 是否开启code为0时的信息提示, 默认为false
showSuccessMessage?: boolean
// 当前请求使用另外的用户token
anotherToken?: string
}