您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何封裝一個好用的axios的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇如何封裝一個好用的axios文章都會有所收獲,下面我們一起來看看吧。
列一下我想要這個通用請求能達到什么樣的效果
1.正常請求該有的(跨域攜帶cookie,token,超時設置)
2.請求響應攔截器
請求成功,業務狀態碼200,解析result給我,我不想一層一層的去判斷拿數據
http請求200, 業務狀態碼非200,說明邏輯判斷這是不成功的,那就全局message提示服務端的報錯
http請求非200, 說明http請求都有問題,也全局message提示報錯
http請求或者業務狀態碼401都做注銷操作
3.全局的loading配置, 默認開啟,可配置關閉(由于后端的問題,經常會讓前端加防抖節流或者loading不讓用戶在界面上瘋狂亂點,行吧行吧,你們的問題前端幫你們解決,你的規矩就是規矩是吧????)
4.統一文件下載處理 (不要再去各寫各的下載了,你寫一個,他寫一個,一個項目就是這樣整的跟屎一樣)
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = axios.create({ timeout: 1000, //超時配置 withCredentials: true, //跨域攜帶cookie ...config, // 自定義配置覆蓋基本配置 }); return instance; };
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; import { Message } from "element-ui"; import { jumpLogin } from "@/utils"; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = axios.create({ timeout: 1000, //超時配置 withCredentials: true, //跨域攜帶cookie ...config, // 自定義配置覆蓋基本配置 }); // 添加請求攔截器 instance.interceptors.request.use( function (config: any) { // 在發送請求之前做些什么 console.log("config:", config); // config.headers.Authorization = vm.$Cookies.get("vue_admin_token"); return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); } ); // 添加響應攔截器 instance.interceptors.response.use( function (response) { // 對響應數據做點什么 console.log("response:", response); const { code, data, message } = response.data; if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { Message.error(message); return Promise.reject(response.data); } }, function (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) { jumpLogin(); } } Message.error(error?.response?.data?.message || "服務端異常"); return Promise.reject(error); } ); return instance; };
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; import { Message } from "element-ui"; import { jumpLogin } from "@/utils"; import { Loading } from "element-ui"; import { ElLoadingComponent } from "element-ui/types/loading"; // import vm from "@/main"; let loadingInstance: ElLoadingComponent | null = null; let requestNum = 0; const addLoading = () => { // 增加loading 如果pending請求數量等于1,彈出loading, 防止重復彈出 requestNum++; if (requestNum == 1) { loadingInstance = Loading.service({ text: "正在努力加載中....", background: "rgba(0, 0, 0, 0)", }); } }; const cancelLoading = () => { // 取消loading 如果pending請求數量等于0,關閉loading requestNum--; if (requestNum === 0) loadingInstance?.close(); }; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = axios.create({ timeout: 1000, //超時配置 withCredentials: true, //跨域攜帶cookie ...config, // 自定義配置覆蓋基本配置 }); // 添加請求攔截器 instance.interceptors.request.use( function (config: any) { // 在發送請求之前做些什么 const { loading = true } = config; console.log("config:", config); // config.headers.Authorization = vm.$Cookies.get("vue_admin_token"); if (loading) addLoading(); return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); } ); // 添加響應攔截器 instance.interceptors.response.use( function (response) { // 對響應數據做點什么 console.log("response:", response); const { loading = true } = response.config; if (loading) cancelLoading(); const { code, data, message } = response.data; if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { Message.error(message); return Promise.reject(response.data); } }, function (error) { // 對響應錯誤做點什么 console.log("error-response:", error.response); console.log("error-config:", error.config); console.log("error-request:", error.request); const { loading = true } = error.config; if (loading) cancelLoading(); if (error.response) { if (error.response.status === 401) { jumpLogin(); } } Message.error(error?.response?.data?.message || "服務端異常"); return Promise.reject(error); } ); return instance; };
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; import { Message } from "element-ui"; import { jumpLogin, downloadFile } from "@/utils"; import { Loading } from "element-ui"; import { ElLoadingComponent } from "element-ui/types/loading"; // import vm from "@/main"; let loadingInstance: ElLoadingComponent | null = null; let requestNum = 0; const addLoading = () => { // 增加loading 如果pending請求數量等于1,彈出loading, 防止重復彈出 requestNum++; if (requestNum == 1) { loadingInstance = Loading.service({ text: "正在努力加載中....", background: "rgba(0, 0, 0, 0)", }); } }; const cancelLoading = () => { // 取消loading 如果pending請求數量等于0,關閉loading requestNum--; if (requestNum === 0) loadingInstance?.close(); }; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = axios.create({ timeout: 1000, //超時配置 withCredentials: true, //跨域攜帶cookie ...config, // 自定義配置覆蓋基本配置 }); // 添加請求攔截器 instance.interceptors.request.use( function (config: any) { // 在發送請求之前做些什么 const { loading = true } = config; console.log("config:", config); // config.headers.Authorization = vm.$Cookies.get("vue_admin_token"); if (loading) addLoading(); return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); } ); // 添加響應攔截器 instance.interceptors.response.use( function (response) { // 對響應數據做點什么 console.log("response:", response); const { loading = true } = response.config; if (loading) cancelLoading(); const { code, data, message } = response.data; // config設置responseType為blob 處理文件下載 if (response.data instanceof Blob) { return downloadFile(response); } else { if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { Message.error(message); return Promise.reject(response.data); } } }, function (error) { // 對響應錯誤做點什么 console.log("error-response:", error.response); console.log("error-config:", error.config); console.log("error-request:", error.request); const { loading = true } = error.config; if (loading) cancelLoading(); if (error.response) { if (error.response.status === 401) { jumpLogin(); } } Message.error(error?.response?.data?.message || "服務端異常"); return Promise.reject(error); } ); return instance; };
src/utils/index.ts import { Message } from "element-ui"; import { AxiosResponse } from "axios"; import vm from "@/main"; /** * 跳轉登錄 */ export const jumpLogin = () => { vm.$Cookies.remove("vue_admin_token"); vm.$router.push(`/login?redirect=${encodeURIComponent(vm.$route.fullPath)}`); }; /** * 下載文件 * @param response * @returns */ export const downloadFile = (response: AxiosResponse) => { console.log("response.data.type:", response.data.type); return new Promise((resolve, reject) => { const fileReader = new FileReader(); fileReader.onload = function () { try { console.log("result:", this.result); const jsonData = JSON.parse((this as any).result); // 成功 說明是普通對象數據 if (jsonData?.code !== 200) { Message.error(jsonData?.message ?? "請求失敗"); reject(jsonData); } } catch (err) { // 解析成對象失敗,說明是正常的文件流 const blob = new Blob([response.data]); // 本地保存文件 const url = window.URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; const filename = response?.headers?.["content-disposition"] ?.split("filename*=")?.[1] ?.substr(7); link.setAttribute("download", decodeURI(filename)); document.body.appendChild(link); link.click(); resolve(response.data); } }; fileReader.readAsText(response.data); }); };
import { createAxiosByinterceptors } from "@/api/request"; const request = createAxiosByinterceptors({ baseURL: localhost:7007, }); //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", });
關于“如何封裝一個好用的axios”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“如何封裝一個好用的axios”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。