vue封裝axios的兩種方法總結(jié)
作為前端工程師,經(jīng)常需要對axios進行封裝以滿足復(fù)用的目的。在不同的前端項目中使用相同的axios封裝有利于保持一致性,有利于數(shù)據(jù)之間的傳遞和處理。本文提供兩種對axios進行封裝的思路。
1. 將請求方式作為調(diào)用參數(shù)傳遞進來
1.首先導(dǎo)入了axios, AxiosInstance和AxiosResponse模塊,用于創(chuàng)建一個http請求的實例和處理響應(yīng)結(jié)果。
2.定義了一個getBaseUrl函數(shù),用于獲取請求的基礎(chǔ)URL。
3.創(chuàng)建了httpProto實例,使用axios.create方法進行創(chuàng)建。并配置了請求的超時時間為5000ms,不攜帶憑證,設(shè)置請求的Content-Type為application/json;charset=UTF-8,并允許跨域訪問。
4.添加了一個請求攔截器,通過httpProto.interceptors.request.use方法,對請求進行處理。首先使用getBaseUrl函數(shù)獲取基礎(chǔ)URL,并將其添加到請求的baseURL屬性中。然后通過getToken函數(shù)獲取憑證,如果憑證存在,則將其添加到請求的Authorization頭部字段中。最后返回處理后的請求配置。
5.添加了一個響應(yīng)攔截器,通過httpProto.interceptors.response.use方法,對響應(yīng)進行處理。首先獲取響應(yīng)的data字段,然后判斷data.result的值,如果為0則表示請求成功,直接返回data。否則將返回一個失敗的Promise,reject的值為data。
6.定義了一個http函數(shù),用于發(fā)送請求。這個函數(shù)接收一個method參數(shù)和其他參數(shù)(rest),然后通過httpProto[method](...rest)的形式調(diào)用httpProto實例的對應(yīng)方法發(fā)送請求。
7定義了一個urls對象,用于存儲可供使用的URL路徑,其中有一個示例路徑example。
7.定義了一個methods對象,用于存儲常用的請求方法名稱,包括get、post和delete。
完整的代碼如下所示:
import axios, { AxiosInstance, AxiosResponse } from "axios";
import { getToken } from "./token";
// 獲取請求的基礎(chǔ)URL
const getBaseUrl = () => `http://${window.constant.serverIp}:8888}`;
// 創(chuàng)建http請求的實例對象
const httpProto: AxiosInstance = axios.create({
timeout: 5000,
withCredentials: false,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
}
});
// 添加請求攔截器
httpProto.interceptors.request.use((config: any) => {
// 配置baseURL
config.baseURL = getBaseUrl();
// 獲取憑證
const token = getToken();
if (token) {
// 如果有憑證就加上此憑證
config.headers.Authorization = `${token}`;
}
return config;
}, (error) => {
return Promise.reject(error)
});
// 添加響應(yīng)攔截器
httpProto.interceptors.response.use(
(response: AxiosResponse) => {
const { data } = response
// 統(tǒng)一處理響應(yīng)結(jié)果
if (data.result === 0) {
return data;
} else {
return Promise.reject(data);
}
},
(error) => {
// 統(tǒng)一處理錯誤信息
return Promise.reject(error);
}
);
// 將httpProto實例,也就是AxiosInstance實例對象封裝起來
const http = (method: string, ...rest: any) => {
return httpProto[method](...rest);
}
// 可供使用的urls
const urls = {
example: `/prod/example`,
}
const methods = {
get: 'get',
post: 'post',
delete: 'delete',
}
export { http, urls, methods };2. 直接調(diào)用某請求方式對應(yīng)的請求方法
1.導(dǎo)入了axios模塊的相關(guān)類型和函數(shù)。
2.定義了printLog函數(shù),用于處理日志輸出。
3.定義了IResponse接口,表示請求響應(yīng)對象的格式。
4.定義了RequestParams接口,表示發(fā)送請求的配置項的格式。
5.定義了IHttp接口,表示封裝對象支持的請求方式/方法。
6.定義了req對象,用于向外暴露支持的請求方法。
7.定義了methods數(shù)組,表示支持的請求方式類型。
8.使用forEach方法遍歷methods數(shù)組,逐步構(gòu)造req對象上的各個方法。
9.在每個方法的構(gòu)造過程中,進行以下步驟:
- 參數(shù)合并,將默認的responseType設(shè)置為'json'。
- 從params對象中解構(gòu)需要的參數(shù)。
- 使用axios.create方法創(chuàng)建一個AxiosInstance實例對象。
- 創(chuàng)建請求頭對象,并設(shè)置一些常用的請求頭信息。
- 構(gòu)造請求配置對象AxiosRequestConfig。
- 根據(jù)請求方式對請求配置進行修正,主要是將data賦值到相應(yīng)的字段中。
- 添加請求攔截器,并在成功和失敗的情況下返回配置。
- 添加響應(yīng)攔截器,并在成功和失敗的情況下返回處理結(jié)果。
- 構(gòu)造請求成功的回調(diào)函數(shù),對返回數(shù)據(jù)進行格式化的操作。
- 構(gòu)造請求失敗的回調(diào)函數(shù),處理錯誤日志和斷網(wǎng)情況。
- 發(fā)送請求并將請求結(jié)果作為函數(shù)的返回值。
10.默認導(dǎo)出req對象。
以下是加上注釋的完整代碼:
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
// 日志處理,可定制
const printLog = console;
// 作為被Promise包裹的請求響應(yīng)對象的格式
export interface IResponse {
code: number;
msg: string;
result: {
lastOperaTime: number;
data: any;
};
}
// 發(fā)送請求的配置項的格式
export interface RequestParams {
url: string;
baseUrl?: string;
data?: object;
filter?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';
headers?: any;
timeout?: number;
}
// 封裝對象支持的請求方式/方法
interface IHttp {
get?: (params: RequestParams) => Promise<any>;
post?: (params: RequestParams) => Promise<any>;
put?: (params: RequestParams) => Promise<any>;
patch?: (params: RequestParams) => Promise<any>;
delete?: (params: RequestParams) => Promise<any>;
}
// 支持的請求方式類型
export type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
// 向外暴露出去的對象
const req: IHttp = {};
// 支持的請求類型
const methods: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete'];
// 遍歷methods數(shù)組,逐步構(gòu)造req對象
methods.forEach((_m: HttpMethod) => {
// 使用遍歷的方式對req對象上的各個方法進行構(gòu)造
req[_m] = (params: RequestParams) => {
// 1. 構(gòu)造參數(shù)合并
params = {
...params,
responseType: params.responseType || 'json',
};
// 2. 從使用對象方法的形參上結(jié)構(gòu)出必要的參數(shù)
const {
url, // 服務(wù)器地址
data, // 有效載荷
filter = true, // 過濾器
responseType, // 返回類型
timeout, // 超時時間
} = params;
// 3. 使用axios創(chuàng)建AxiosInstance實例對象
const instance = axios.create({
baseURL: params.baseUrl ?? `http://${window.location.hostname}`,
timeout,
});
// 4. 創(chuàng)建請求頭對象
const headers = {
lastOperaTime: Date.now(), // 時間戳
token: getToken(), // 憑證
lang: getLocalLocale(), // 語言
Accept: 'application/json', // 接受返回數(shù)據(jù)的類型
'Content-Type': 'application/json; charset=utf-8', // 內(nèi)容格式
};
// 5. 請求配置
const axiosConfig: AxiosRequestConfig = {
method: _m, // 請求方法
url, // 服務(wù)器地址
headers: {
// 合并請求頭
...headers,
...(params.headers || {}),
},
responseType, // 返回值類型
};
// 6. 針對不同的請求類型需要對請求配置進行修正
if (data) {
// 對于有效載荷,不同的請求方式攜帶信息的方式是不同的,在這里做了區(qū)分
if (_m === 'get') {
axiosConfig.params = data;
} else if (data instanceof FormData) {
axiosConfig.data = data;
} else {
axiosConfig.data = data;
}
}
// 添加請求攔截器
instance.interceptors.request.use(
// 占位
(config: any) => {
return config;
},
// 失敗則返回失敗
(error: any) => {
return Promise.reject(error);
}
);
// 7. 添加響應(yīng)攔截器
instance.interceptors.response.use(
// 成功的回調(diào),將發(fā)起請求的參數(shù)作為第二參數(shù)回傳
(res: any) => handleSuccess(res, params),
// 失敗的回調(diào),將發(fā)起請求的參數(shù)作為第二參數(shù)回傳
(err: any) => handleError(err, params)
);
// 8. 構(gòu)造請求成功的回調(diào)函數(shù) -- 主要是對返回數(shù)據(jù)進行格式化的操作
function handleSuccess(response: AxiosResponse<IResponse>, requestParams: RequestParams) {
if (response.data) {
// 解構(gòu)數(shù)據(jù)
const { code, msg, result } = response.data;
if (code !== 0) {
printLog.error(msg);
}
return filter ? result?.data ?? result : response.data;
} else {
printLog.error('incorrect data format');
return response.data;
}
}
// 9. 構(gòu)造請求失敗的回調(diào)函數(shù)
function handleError(err: AxiosError, requestParams: RequestParams) {
if (err.response) {
printLog.error(`api: ${requestParams.url}: ${err.response.status}`);
}
if (err instanceof Error) {
if (err.message) {
printLog.error(err.message);
}
}
if (!window.navigator.onLine) {
// 處理斷網(wǎng)情況
printLog.error('netwrok error');
}
return Promise.reject(err);
}
// 10. 發(fā)送請求并將請求結(jié)果(Promise對象)作為函數(shù)的返回值
return instance.request(axiosConfig);
};
});
export default req;到此這篇關(guān)于vue封裝axios的兩種方法總結(jié)的文章就介紹到這了,更多相關(guān)vue封裝axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue Element前端應(yīng)用開發(fā)之echarts圖表
在我們做應(yīng)用系統(tǒng)的時候,往往都會涉及圖表的展示,綜合的圖表展示能夠給客戶帶來視覺的享受和數(shù)據(jù)直觀體驗,同時也是增強客戶認同感的舉措之一2021-05-05
淺析webpack-bundle-analyzer在vue-cli3中的使用
這篇文章主要介紹了webpack-bundle-analyzer在vue-cli3中的使用,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
vue3的ref,computed,reactive和toRefs你都了解嗎
這篇文章主要為大家詳細介紹了vue3的ref,computed,reactive和toRefs,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
Vue常用API、高級API的相關(guān)總結(jié)
這篇文章主要介紹了Vue常用API、高級API的相關(guān)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用vue框架,感興趣的朋友可以了解下2021-02-02
vue3配置router路由并實現(xiàn)頁面跳轉(zhuǎn)功能
這篇文章主要介紹了vue3配置router路由并實現(xiàn)頁面跳轉(zhuǎn),本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
Vue Element-ui實現(xiàn)樹形控件節(jié)點添加圖標詳解
這篇文章主要為大家介紹了Element-ui實現(xiàn)樹形控件節(jié)點添加圖標,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11

