76 lines
1.6 KiB
TypeScript
76 lines
1.6 KiB
TypeScript
import axios from 'axios'
|
|
|
|
export const frontRequest = axios.create({
|
|
baseURL: import.meta.env.VITE_API_FRONT_BASE_URL,
|
|
})
|
|
// 添加请求拦截器
|
|
frontRequest.interceptors.request.use(
|
|
function (config) {
|
|
const token = userStore().frontToken
|
|
if (token !== null || token !== undefined) {
|
|
//添加header
|
|
config.headers.Authorization = token
|
|
}
|
|
// 在发送请求之前做些什么
|
|
return config
|
|
},
|
|
function (error) {
|
|
toast.warning(error.message ?? '未知请求错误')
|
|
// 对请求错误做些什么
|
|
return Promise.reject(error)
|
|
},
|
|
)
|
|
// 添加响应拦截器
|
|
frontRequest.interceptors.response.use(
|
|
function (response) {
|
|
if (response.data.code){
|
|
const code = response.data.code
|
|
switch (code) {
|
|
case 500:
|
|
toast.error(response.data.msg)
|
|
return Promise.reject(response.data.msg)
|
|
case 401:
|
|
window.open(`/login`, '_self')
|
|
toast.error("请重新登录~")
|
|
break
|
|
default:
|
|
return response
|
|
}
|
|
}
|
|
if (response.data) {
|
|
return response.data
|
|
}
|
|
return response
|
|
},
|
|
function (error) {
|
|
const status = error.response?.status
|
|
let { msg, message } = error.response?.data ?? {}
|
|
|
|
if (!msg && message) {
|
|
msg = message
|
|
}
|
|
|
|
if (!msg) {
|
|
switch (status) {
|
|
case 400:
|
|
msg = '参数错误'
|
|
break
|
|
case 500:
|
|
msg = '服务端错误'
|
|
break
|
|
case 401:
|
|
window.location.href = "/dsds"
|
|
break
|
|
default:
|
|
msg = error.message ?? '未知响应错误'
|
|
break
|
|
}
|
|
}
|
|
|
|
toast.warning(msg)
|
|
// 超出 2xx 范围的状态码都会触发该函数。
|
|
// 对响应错误做点什么
|
|
return Promise.reject(error)
|
|
},
|
|
)
|