import axios, {AxiosRequestConfig, AxiosResponse} from "axios"; import type {MessageInstance} from "antd/es/message/interface"; type Req = { messageApi: MessageInstance; url: string; body?: any; config?: AxiosRequestConfig; onBefore?(): void; onSuccess(data: AxiosResponse): void; onFinally?(): void; } axios.defaults.baseURL = 'http://127.0.0.1:7025/copyright'; axios.interceptors.request.use(config => { if (config.method === 'get') { config.data = {unused: 0} // 这个是关键点,解决get 请求添加不上content_type } config.headers['X-USER-ID'] = '80d3365e-0597-4988-979e-18ef1c3ec671'; return config } ); export const Axios = axios; export function get(req: Req) { req.onBefore?.(); Axios.get(req.url, req.config).then(res => { req.onSuccess(res); }).catch(error => { if (error.response) { const data = error.response.data; req.messageApi.open({ type: 'error', content: data.msg ? data.msg : `${data.path}(${data.status})`, }); } else { console.error(error) } }).finally(() => { req.onFinally?.(); }) } export function post(req: Req) { req.onBefore?.(); Axios.post(req.url, req.body, req.config).then(res => { req.onSuccess(res); }).catch(error => { if (error.response) { const data = error.response.data; req.messageApi.open({ type: 'error', content: data.msg ? data.msg : `${data.path}(${data.status})`, }); } else { console.error(error) } }).finally(() => { req.onFinally?.(); }) } export function put(req: Req) { req.onBefore?.(); Axios.put(req.url, req.body, req.config).then(res => { req.onSuccess(res); }).catch(error => { if (error.response) { const data = error.response.data; req.messageApi.open({ type: 'error', content: data.msg ? data.msg : `${data.path}(${data.status})`, }); } else { console.error(error) } }).finally(() => { req.onFinally?.(); }) } export function del(req: Req) { req.onBefore?.(); Axios.delete(req.url, req.config).then(res => { req.onSuccess(res); }).catch(error => { if (error.response) { const data = error.response.data; req.messageApi.open({ type: 'error', content: data.msg ? data.msg : `${data.path}(${data.status})`, }); } else { console.error(error) } }).finally(() => { req.onFinally?.(); }) }