初始化项目
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import axios, { AxiosError } from 'axios'
|
||||
import { createDiscreteApi } from 'naive-ui'
|
||||
import type { ApiResult } from '@/types/http'
|
||||
import { BizError } from '@/types/http'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { router } from '@/router'
|
||||
import { appEnv } from '@/config/env'
|
||||
|
||||
const { message } = createDiscreteApi(['message'])
|
||||
|
||||
const http = axios.create({
|
||||
baseURL: appEnv.apiBaseUrl,
|
||||
timeout: 15000
|
||||
})
|
||||
|
||||
http.interceptors.request.use((config) => {
|
||||
const authStore = useAuthStore()
|
||||
const token = authStore.token
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => {
|
||||
const payload = response.data as ApiResult<unknown>
|
||||
const traceId = response.headers['x-trace-id'] as string | undefined
|
||||
if (!payload || typeof payload.code !== 'string') {
|
||||
return response.data
|
||||
}
|
||||
if (payload.code !== '0') {
|
||||
throw new BizError(payload.code, payload.message || '请求失败', payload.traceId ?? traceId)
|
||||
}
|
||||
return payload.data
|
||||
},
|
||||
async (error: AxiosError<ApiResult<unknown>>) => {
|
||||
const authStore = useAuthStore()
|
||||
const status = error.response?.status
|
||||
const traceId =
|
||||
(error.response?.headers?.['x-trace-id'] as string | undefined) ??
|
||||
error.response?.data?.traceId
|
||||
const backendMessage = error.response?.data?.message
|
||||
|
||||
if (status === 401) {
|
||||
authStore.clearAuth()
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
await router.replace({
|
||||
path: '/login',
|
||||
query: { redirect: router.currentRoute.value.fullPath }
|
||||
})
|
||||
}
|
||||
message.warning(backendMessage ?? '登录已失效,请重新登录')
|
||||
return Promise.reject(new BizError('401', backendMessage ?? '未登录', traceId))
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
if (router.currentRoute.value.path !== '/403') {
|
||||
await router.replace('/403')
|
||||
}
|
||||
message.error(backendMessage ?? '无权限访问该资源')
|
||||
return Promise.reject(new BizError('403', backendMessage ?? '无权限', traceId))
|
||||
}
|
||||
|
||||
const messageText = backendMessage ?? error.message ?? '网络异常,请稍后重试'
|
||||
message.error(traceId ? `${messageText}(追踪ID:${traceId})` : messageText)
|
||||
return Promise.reject(new BizError(String(status ?? 'HTTP_ERROR'), messageText, traceId))
|
||||
}
|
||||
)
|
||||
|
||||
export default http
|
||||
Reference in New Issue
Block a user