system-copyright-react/src/util/AjaxUtils.ts

100 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-03-20 18:30:39 +08:00
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;
}
2024-03-19 19:19:07 +08:00
axios.defaults.baseURL = 'http://127.0.0.1:7025/copyright';
2024-03-20 18:30:39 +08:00
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.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?.();
})
}
2024-03-19 19:19:07 +08:00
2024-03-20 18:30:39 +08:00
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?.();
})
}