axios/index.ts
axios/index.ts
// axios/index.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { IResponse } from "@/utils/axios/type";
import { showMessage } from "./status";
// import NProgress from 'nprogress'
// 如果请求花费了超过 `timeout` 的时间,请求将被中断
axios.defaults.timeout = 5000;
// 表示跨域请求时是否需要使用凭证
axios.defaults.withCredentials = false;
// axios.defaults.headers.common['token'] = AUTH_TOKEN
// 允许跨域
axios.defaults.headers.post["Access-Control-Allow-Origin-Type"] = "*";
const axiosInstance: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_BASE_URL,
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// transformRequest: [
// function (data) {
// //由于使用的 form-data传数据所以要格式化
// delete data.Authorization
// data = qs.stringify(data)
// return data
// },
// ],
});
// axios实例拦截响应
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => {
// if (response.headers.authorization) {
// localStorage.setItem('app_token', response.headers.authorization)
// } else if (response.data && response.data.token) {
// localStorage.setItem('app_token', response.data.token)
// }
if (response.status === 200) {
return response;
}
showMessage(response.status);
return response;
},
// 请求失败
(error: any) => {
const { response } = error;
if (response) {
showMessage(response.status);
return Promise.reject(response.data);
}
showMessage("网络连接异常,请稍后再试!");
}
);
const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
const conf = config;
return new Promise((resolve) => {
axiosInstance
.request<any, AxiosResponse<IResponse>>(conf)
.then((res: AxiosResponse<IResponse>) => {
const { data } = res;
resolve(data as T);
});
});
};
export function get<T = any>(config: AxiosRequestConfig): Promise<T> {
return request({ ...config, method: "GET" });
}
export function post<T = any>(config: AxiosRequestConfig): Promise<T> {
return request({ ...config, method: "POST" });
}
export function del<T = any>(config: AxiosRequestConfig): Promise<T> {
return request({ ...config, method: "DELETE" });
}
export function put<T = any>(config: AxiosRequestConfig): Promise<T> {
return request({ ...config, method: "PUT" });
}
export default request;
export type { AxiosInstance, AxiosResponse };
/**
* @description: 用户登录案例
* @params {ILogin} params
* @return {Promise}
*/
// export const login = (params: ILogin): Promise<IResponse> => {
// return axiosInstance.post('user/login', params).then(res => res.data);
// };
axios/type.ts
axios/type.ts
export interface IResponse<T = any> {
statusCode: number;
message: string;
data?: T;
}
axios/status.ts
axios/status.ts
export const showMessage = (status: number | string): string => {
let message = "";
switch (status) {
case 400:
message = "请求错误(400)";
break;
case 401:
message = "未授权,请重新登录(401)";
break;
case 403:
message = "拒绝访问(403)";
break;
case 404:
message = "请求出错(404)";
break;
case 408:
message = "请求超时(408)";
break;
case 500:
message = "服务器错误(500)";
break;
case 501:
message = "服务未实现(501)";
break;
case 502:
message = "网络错误(502)";
break;
case 503:
message = "服务不可用(503)";
break;
case 504:
message = "网络超时(504)";
break;
case 505:
message = "HTTP版本不受支持(505)";
break;
default:
message = `连接出错(${status})!`;
}
return `${message},请检查网络或联系管理员!`;
};
使用
index.ts
import { get } from "@/utils/axios";
import { IResponse } from "@/utils/axios/type";
import { DDQueryDto } from "./types";
// 要注意区分,params 和 data 两种参数传递
const getDD = async (params?: DDQueryDto) =>
get<IResponse>({ url: "/dangdang", params });
export { getDD };
// 调用
getDD().then((res) => {
console.log(res);
});
types.ts
export interface DDQueryDto {
id?: number;
searchAuthor?: string;
searchTitle?: string;
random?: number;
}