1. 函数方式
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import { Message } from "view-ui-plus";export const createAxiosByinterceptors = (config?: AxiosRequestConfig
): AxiosInstance => {const instance = axios.create({timeout: 1000, //超时配置withCredentials: true, //跨域携带cookie...config, // 自定义配置覆盖基本配置});// 添加请求拦截器instance.interceptors.request.use((config: any) => {// 在发送请求之前做些什么console.log("config:", config);return config;},(error) => {// 对请求错误做些什么return Promise.reject(error);});// 添加响应拦截器instance.interceptors.response.use((response) => {// 对响应数据做点什么console.log("response:", response);const { code, data, message } = response.data;if (code === 200) return data;else if (code === 401) {// 退出处理} else {Message.error(message);return Promise.reject(response.data);}},(error) => {// 对响应错误做点什么console.log("error-response:", error.response);console.log("error-config:", error.config);console.log("error-request:", error.request);if (error.response) {if (error.response.status === 401) {// 退出处理}}Message.error(error?.response?.data?.message || "服务端异常");return Promise.reject(error);});return instance;
};
使用方法
import { createAxiosByinterceptors } from "@/service/service";const request = createAxiosByinterceptors({baseURL: "/sdkjfdk",
});//lodaing配置
export const appList = (params: any): Promise<any> =>request.get("/app", { params, loading: true }); // 不需要默认的全局loading效果可配置loading为false关闭 loading默认为true// 文件下载
export const exportGoods = (data: any) =>request.post("/export", data, {responseType: "blob",});export const expordtGoods = (data: any) =>request.put("/export", data, {responseType: "blob",});
讲解:函数式通过调用方法创建axios实例,通过参数传入基础url,超时时间等定义参数。
使用时比较接近axios写法。
2. 类方法
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from 'view-design';
const $Message: any = Message;
export class HttpService {private instance: AxiosInstance;baseConfig: AxiosRequestConfig = { baseURL: "/commonApi" };constructor(baseURL?: string, timeout?: number) {// 使用axios.create创建axios实例this.instance = axios.create({ ...this.baseConfig, baseURL, timeout });// 请求拦截器this.instance.interceptors.request.use((config: AxiosRequestConfig) => {return config;}, (error: any) => {return Promise.reject(error);})// 响应拦截器this.instance.interceptors.response.use((response: AxiosResponse) => {if (response.request.responseType === 'blob') { // 流文件return response}const { retcode, code, status, message, msg, desc } = response.data;let msgStr = message || msg || desc || '系统异常,请联系管理员';if ((retcode && retcode === 200) || (code && code === 0)) {return Promise.resolve(response.data);} else if (!status) {return Promise.resolve(response.data);} else {$Message.error(msgStr);return Promise.reject(response.data);}}, (error: any) => {const { status, data } = error.responseconst { msg, message, desc } = dataconst errMsg = msg || message || desc || '系统异常,请联系管理员';switch (status) {case 401:// 这里可以做清空storage并跳转到登录页的操作case 400:case 403:case 404:case 408:case 500:case 501:case 502:case 503:case 504:case 505:default:$Message.error(errMsg);}return Promise.reject(error);})}/*** commonRequest*/public commonRequest(config: AxiosRequestConfig): Promise<AxiosResponse> {return this.instance(config)}
}
使用方法
import { HttpService } from '../interceptors'const proxyPrefix: string = '/proxyApi';
const $docQaReq: any = new HttpService(proxyPrefix)export const apiUrl = {docFileUpload: `${proxyPrefix}/doc/semantic-doc/document/file/upload`,
}/*** @description 获取所有文档库标签(以及文档* @param type 1 为文档标签,不传则为文档库标签*/
export const getAllLibLabel = (data?: {type: number;
}) => {return $docQaReq.commonRequest({url: `/doc/semantic-doc/label/list`,method: 'get',params: data? data: null})
}/*** @description 新增文档库标签(以及文档* @param type 1 为文档标签,不传则为文档库标签*/
export const creatLibLabel = (data: {name: string;type?: number;
}) => {return $docQaReq.commonRequest({url: '/doc/semantic-doc/label/create',method: 'post',data})
}
类方法: 通过创建一个类,传入baseUrl,超时时间等自定义参数。使用时候调用类的方法实现创建axios实例。
两种方法写法不同,功能相同。