赞
踩
注意:axios版本:1.4
import axios from "axios"; import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig, } from "axios"; // 定义一个常见后端请求返回 type BaseApiResponse<T> = { code: number; message: string; result: T; }; // 拓展 axios 请求配置,加入我们自己的配置 interface RequestOptions { // 是否全局展示请求 错误信息 globalErrorMessage?: boolean; // 是否全局展示请求 成功信息 globalSuccessMessage?: boolean; } // 拓展自定义请求配置 interface ExpandAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { interceptorHooks?: InterceptorHooks; requestOptions?: RequestOptions; } // 拓展 axios 请求配置 interface ExpandInternalAxiosRequestConfig<D = any> extends InternalAxiosRequestConfig<D> { interceptorHooks?: InterceptorHooks; requestOptions?: RequestOptions; } // 拓展 axios 返回配置 export interface ExpandAxiosResponse<T = any, D = any> extends AxiosResponse<T, D> { config: ExpandInternalAxiosRequestConfig<D>; } export interface InterceptorHooks { requestInterceptor?: ( config: InternalAxiosRequestConfig ) => InternalAxiosRequestConfig; requestInterceptorCatch?: (error: any) => any; responseInterceptor?: ( response: AxiosResponse ) => AxiosResponse | Promise<AxiosResponse>; responseInterceptorCatch?: (error: any) => any; } // 导出Request类,可以用来自定义传递配置来创建实例 export default class MyRequest { // axios 实例 private _instance: AxiosInstance; // 默认配置 private _defaultConfig: ExpandAxiosRequestConfig = { baseURL: "", timeout: 5000, requestOptions: { globalErrorMessage: true, globalSuccessMessage: false, }, }; private _interceptorHooks?: InterceptorHooks; constructor(config: ExpandAxiosRequestConfig) { // 使用axios.create创建axios实例 this._instance = axios.create(Object.assign(this._defaultConfig, config)); this._interceptorHooks = config.interceptorHooks; this.setupInterceptors(); } // 通用拦截,在初始化时就进行注册和运行,对基础属性进行处理 private setupInterceptors() { this._instance.interceptors.request.use( this._interceptorHooks?.requestInterceptor, this._interceptorHooks?.requestInterceptorCatch ); this._instance.interceptors.response.use( this._interceptorHooks?.responseInterceptor, this._interceptorHooks?.responseInterceptorCatch ); } // 定义核心请求 public request(config: ExpandAxiosRequestConfig): Promise<AxiosResponse> { return this._instance.request(config); } public get<T = any>( url: string, config?: ExpandAxiosRequestConfig ): Promise<AxiosResponse<BaseApiResponse<T> | any>> { return this._instance.get(url, config); } public post<T = any>( url: string, data?: any, config?: ExpandAxiosRequestConfig ): Promise<T> { return this._instance.post(url, data, config); } public put<T = any>( url: string, data?: any, config?: ExpandAxiosRequestConfig ): Promise<T> { return this._instance.put(url, data, config); } public delete<T = any>( url: string, config?: ExpandAxiosRequestConfig ): Promise<T> { return this._instance.delete(url, config); } public postXForm<T = any>(url: string, data?: any): Promise<T> { return this._instance.post(url, data, { // 利用 transformRequest 进行转换配置 transformRequest: [ function (oldData) { let newStr = ""; for (let item in oldData) { newStr += encodeURIComponent(item) + "=" + encodeURIComponent(oldData[item]) + "&"; } newStr = newStr.slice(0, -1); return newStr; }, ], headers: { "Content-Type": "application/x-www-form-urlencoded", }, }); } }
先实例化一个MyRequest对象,export出去使用
import MyRequest, { InterceptorHooks, ExpandAxiosResponse } from "./axios"; // 请求拦截器 const transform: InterceptorHooks = { requestInterceptor(config) { // 请求头部处理,如添加 token const token = localStorage.getItem("accessToken"); if (token) { config!.headers!.Authorization = token; } return config; }, requestInterceptorCatch(err) { // 请求错误,这里可以用全局提示框进行提示 return Promise.reject(err); }, // 请求拦截 responseInterceptor(result) { // 因为 axios 返回不支持扩展自定义配置,需要自己断言一下 const res = result as ExpandAxiosResponse; return res.data; }, // 响应拦截 responseInterceptorCatch(err) { return Promise.reject(err.response); }, }; const request = new MyRequest({ baseURL: "", timeout: 5000, interceptorHooks: transform, }); export default request;
// 定义请求返回 interface ResModel { str: string num: number } // 发起请求 request .post<ResModel>( '/abc', { a: 'aa', b: 'bb' }, { requestOptions: { globalErrorMessage: true } } ) .then((res) => { console.log('res: ', res) console.log(res.str) })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。