优化:优化前端 axios 配置

This commit is contained in:
2023-02-02 20:26:42 +08:00
parent c5d4e8ae21
commit b32a298b62
6 changed files with 73 additions and 62 deletions

View File

@@ -1,55 +0,0 @@
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
export interface HttpResponse<T = unknown> {
success: boolean; // 是否成功
code: number; // 状态码
msg: string; // 状态信息
timestamp: string; // 时间戳
data: T; // 返回数据
}
if (import.meta.env.VITE_API_BASE_URL) {
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}
axios.interceptors.request.use(
(config: AxiosRequestConfig) => {
// let each request carry token
// this example using the JWT token
// Authorization is a custom headers key
// please modify it according to the actual situation
const token = getToken();
if (token) {
if (!config.headers) {
config.headers = {};
}
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// do something
return Promise.reject(error);
}
);
// add response interceptors
axios.interceptors.response.use(
(response: AxiosResponse<HttpResponse>) => {
const res = response.data;
if (!res.success) {
Message.error(res.msg);
}
return res;
},
(error) => {
const res = error.response.data;
Message.error({
content: res.msg || '网络错误',
duration: 3 * 1000,
});
return Promise.reject(error);
}
);

View File

@@ -1,6 +1,8 @@
import axios from 'axios';
import qs from 'query-string';
const BASE_URL = '/system/dept';
export interface DeptRecord {
deptId?: number;
deptName: string;
@@ -21,7 +23,7 @@ export interface DeptParams {
}
export function listDept(params: DeptParams) {
return axios.get<DeptRecord[]>('/system/dept/all', {
return axios.get<DeptRecord[]>(`${BASE_URL}/all`, {
params,
paramsSerializer: (obj) => {
return qs.stringify(obj);
@@ -30,17 +32,17 @@ export function listDept(params: DeptParams) {
}
export function getDept(id: number) {
return axios.get<DeptRecord>(`/system/dept/${id}`);
return axios.get<DeptRecord>(`${BASE_URL}/${id}`);
}
export function createDept(req: DeptRecord) {
return axios.post('/system/dept', req);
return axios.post(BASE_URL, req);
}
export function updateDept(req: DeptRecord) {
return axios.put(`/system/dept`, req);
return axios.put(BASE_URL, req);
}
export function deleteDept(ids: number | Array<number>) {
return axios.delete(`/system/dept/${ids}`);
return axios.delete(`${BASE_URL}/${ids}`);
}