|
|
@@ -0,0 +1,50 @@
|
|
|
+import axios from 'axios'
|
|
|
+import { showToast } from 'vant'
|
|
|
+
|
|
|
+export class PortalError extends Error {
|
|
|
+ code?: number
|
|
|
+ constructor(message: string, code?: number) {
|
|
|
+ super(message)
|
|
|
+ this.code = code
|
|
|
+ this.name = 'PortalError'
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+const portalClient = axios.create({
|
|
|
+ baseURL: import.meta.env.VITE_API_URL || '/api',
|
|
|
+ timeout: 60000,
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
+})
|
|
|
+
|
|
|
+portalClient.interceptors.request.use((config) => {
|
|
|
+ const token = localStorage.getItem('accessToken')
|
|
|
+ if (token) {
|
|
|
+ config.headers.Authorization = `Bearer ${token}`
|
|
|
+ }
|
|
|
+ return config
|
|
|
+})
|
|
|
+
|
|
|
+portalClient.interceptors.response.use(
|
|
|
+ (res) => {
|
|
|
+ const body = res.data
|
|
|
+ if (body && typeof body.code === 'number' && body.code !== 200) {
|
|
|
+ const msg = body.message || body.msg || '请求失败'
|
|
|
+ showToast(msg)
|
|
|
+ return Promise.reject(new PortalError(msg, body.code))
|
|
|
+ }
|
|
|
+ return body
|
|
|
+ },
|
|
|
+ (err) => {
|
|
|
+ if (err.response?.status !== 401) {
|
|
|
+ const msg =
|
|
|
+ err.response?.data?.message ||
|
|
|
+ err.response?.data?.msg ||
|
|
|
+ err.message ||
|
|
|
+ '网络异常'
|
|
|
+ showToast(msg)
|
|
|
+ }
|
|
|
+ return Promise.reject(err)
|
|
|
+ },
|
|
|
+)
|
|
|
+
|
|
|
+export default portalClient
|