1.首先安装
npm i axios
2.在项目根目录创建
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios'; import { ElMessage } from 'element-plus'; import { getMessageInfo } from './status'; /** * 接口默认返回的数据格式 */ interface BaseResponse<T = any> { code: number | string; message: string; data: T; status?: number | string; } // 创建axios const service = axios.create({ baseURL: import.meta.env.VITE_APP_BASE_API, timeout: 15000, }); // axios实例拦截请求 service.interceptors.request.use( (config: InternalAxiosRequestConfig) => { return config; }, (error: AxiosError) => { return Promise.reject(error); } ); // axios实例拦截响应 service.interceptors.response.use( (response: AxiosResponse) => { if (response.status === 200) { return response.data; } // 如果返回状态不等于200,就调用getMessageInfo()返回错误信息 ElMessage({ message: getMessageInfo(response.status), type: 'error', }); return response.data; }, // 请求失败 (error: any) => { const { response } = error; if (response) { ElMessage({ message: getMessageInfo(response.status), type: 'error', }); return Promise.reject(response.data); } // getMessageInfo()中没有定义的错误信息统一提示该提示 ElMessage({ message: '网络连接异常,请稍后再试!', type: 'error', }); } ); // 此处相当于二次响应拦截 // 为响应数据进行定制化处理 const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => { const conf = config; return new Promise((resolve, reject) => { service.request<any, AxiosResponse<BaseResponse>>(conf).then((res: AxiosResponse<BaseResponse>) => { const data = res.data; // 如果data.code为错误代码返回message信息 if (data.code != 0) { ElMessage({ message: data.message, type: 'error', }); reject(data.message); } else { ElMessage({ message: data.message, type: 'success', }); // 此处返回data信息 也就是 api 中配置好的 Response类型 resolve(data.data as T); } }); }); }; export function get<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> { return requestInstance({ ...config, url, method: 'GET', params: parms }); } export function post<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> { return requestInstance({ ...config, url, method: 'POST', data: data }); } export function put<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> { return requestInstance({ ...config, url, method: 'PUT', params: parms }); } export function del<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> { return requestInstance({ ...config, url, method: 'DELETE', data: data }); } // 一般的后端返回的数据结构 // { // 'code': 1, // 'message': '成功', // 'data': { // 'id': 1, // 'name': '张三', // 'age': 18, // 'sex': 1, // 'address': '北京市', // 'createTime': '2021-08-30 15:49:16', // 'updateTime': '2021-08-30 15:49:16', // 'deleteTime': null, // 'createBy': 1, // 'updateBy': 1, // } // }
export const getMessageInfo = (status: number | string): string => { let msg = ''; switch (status) { case 400: msg = '请求错误(400)'; break; case 403: msg = '拒绝访问(403)'; break; case 401: msg = '未授权(401)'; break; case 500: msg = '服务器错误(500)'; break; case 503: msg = '服务不可用(503)'; break; default: msg = `连接出错(${status})!`; } return msg; };
3.项目根目录下新建一个
以用户模块演示就是在
import { post, get } from '@/http/request'; // 请求参数类型 export type LoginRequest = { username: string; password: string; }; // 刷新登录信息需要的参数 export type reLoginRequest = { accessToken: string; }; //响应数据定制化类型 export type LoginResponse = { username: string; roles: string[]; accessToken: string; }; // 定义的接口 export const userLogin = async (data?: LoginRequest) => { return post<LoginResponse>({}, '/login', data); }; export const refreshUserInfo = async (data?: reLoginRequest) => { return post<LoginResponse>({}, '/getUserInfo', data); };