import axios from 'axios'; import {BizError} from "./types.ts"; import Storage from "./storage.ts"; import {useUserinfoStore} from "../store/userinfoStore.ts"; import {APP_CONFIG} from "../config.ts"; export interface APIResponse { /** * 错误码,0:成功,其他失败 */ code: number; data?: T; /** * 非0情况下,提示信息 */ msg: string; } // const baseURL = APP_CONFIG.API_PREFIX; // const FORM_FORMAT = 'application/x-www-form-urlencoded'; const JSON_FORMAT = 'application/json'; export type RequestMethod = 'get' | 'post' | 'put' | 'delete' const Axios = axios.create({ baseURL: APP_CONFIG.API_PREFIX, timeout: 120000, // 超时时长120s headers: { 'Content-Type': JSON_FORMAT } }) // 请求前拦截 Axios.interceptors.request.use(config => { const token = Storage.get(APP_CONFIG.LOGIN_TOKEN_KEY) // const {token} = useUserinfoStore() if (token) { config.headers['Authorization'] = `${token}`; // Bearer } if (config.data && config.data instanceof FormData) { config.headers['Content-Type'] = 'multipart/form-data'; } return config }, err => { return Promise.reject(err) }) // // // 返回后拦截 Axios.interceptors.response.use(res => { return res }, err => { err.message = '服务异常,请稍后再试'; if (err.message === 'Network Error') { err.message = '网络连接异常!'; } else if (err.code === 'ECONNABORTED') { err.message = '请求超时,请稍后再试'; } return Promise.reject(err) }) export function request(url: string, method: RequestMethod, data: any = null, getOriginResult = false) { return new Promise((resolve, reject) => { Axios.request>({ url, method, data, }).then(res => { if (res.status != 200) { reject(new BizError("服务异常,请稍后再试", res.status)) return; } const {code, msg, data} = res.data if (code == 0) { if (getOriginResult) { resolve(res.data as any) return; } resolve(data as any as T) } else { if (code == 403) { const state = useUserinfoStore.getState() // 未登录 显示登录modal // state.showLogin(true); } reject(new BizError(msg, code)) } }).catch(e => { console.log(e) reject(new BizError(e.message, 500)) }) }) } export function uploadFile(url: string, file: File, data: any = {}, returnOrigin = false) { const formData = new FormData(); formData.append('file', file); if (data) { for (const key in data) { formData.append(key, data[key]) } } return request(url, 'post', formData, returnOrigin) } export function post(url: string, data: any = {}) { return request(url, 'post', data) } export function get(url: string, data: any = {}) { return request(url, 'get', data) }