Preface
At the project launch meeting, everyone scheduled various schedules and plans. Most of the people focused on the back-end technical solutions. Everyone seemed to think that there was nothing to do in the front-end preparations at the front, and didn’t they have ready-made scaffolding? Haven’t others done everything for you? 💉💉I lost it. . . . What you said seems to be unreasonable, but have you really used official scaffolding? In addition to helping me generate project directories and package and compile configurations, there are still some framework-level things that I have to do by myself. I don’t care about it, you all have to start the schedule, I want it too! ! 🔫
Think about what you need to do
I have won a week of preparation (skipping fish), and the main thing is that the big guys on the back end are going to fight for it. I can only be on par with them, hahahaha. First use vue-cli to generate a project. Think about what to do. I thought about the previous project general request capability encapsulation was not very good in the early stage, which led to a lot of redundant code written later, which really disgusting me. Then I have to make this whole thing in the early stage🙌🙌
General capability
List what effect I want this general request to achieve
1. Normally request what should be (cross-domain carrying cookies, tokens, timeout settings)
2. Request response interceptor
- The request was successful, the business status code was 200, and the analysis result was given to me. I don't want to judge and get data layer by layer.
- http request 200, the service status code is not 200, which means that the logical judgment is unsuccessful, then the global message prompts the server for an error.
- The http request is not 200, which means that there are problems with the http request, and the global message prompts an error.
- Both http request or business status code 401 do cancellation operations
3. Global loading configuration, enabled by default, can be configured to turn off (due to back-end problems, the front-end will often add anti-shake throttling or loading to prevent users from being crazy on the interface. OK, OK, the front-end will help you solve your problem, your rules are the rules, right?)
4. Unified file download processing (don’t write each one to download it anymore. You write one, and he writes one, and a project is like this)
Add functions step by step
Normal requests
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = ({ timeout: 1000, //Timeout configuration withCredentials: true, //Carry cookies across domains ...config, // Custom configuration covers basic configuration }); return instance; };
Request response interceptor
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; import { Message } from "element-ui"; import { jumpLogin } from "@/utils"; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = ({ timeout: 1000, //Timeout configuration withCredentials: true, //Carry cookies across domains ...config, // Custom configuration covers basic configuration }); // Add a request interceptor ( function (config: any) { // What to do before sending a request ("config:", config); // = vm.$("vue_admin_token"); return config; }, function (error) { // What to do about the request error return (error); } ); // Add a response interceptor ( function (response) { // Do something about the response data ("response:", response); const { code, data, message } = ; if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { (message); return (); } }, function (error) { // Do something to respond to errors ("error-response:", ); ("error-config:", ); ("error-request:", ); if () { if ( === 401) { jumpLogin(); } } (error?.response?.data?.message || "Server side exception"); return (error); } ); return instance; };
Global loading configuration
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 = () => { // Increase loading If the number of pending requests is equal to 1, loading will be popped up to prevent repeated popups requestNum++; if (requestNum == 1) { loadingInstance = ({ text: "It's working hard to load...", background: "rgba(0, 0, 0, 0)", }); } }; const cancelLoading = () => { // Cancel loading If the number of pending requests is equal to 0, close loading requestNum--; if (requestNum === 0) loadingInstance?.close(); }; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = ({ timeout: 1000, //Timeout configuration withCredentials: true, //Carry cookies across domains ...config, // Custom configuration covers basic configuration }); // Add a request interceptor ( function (config: any) { // What to do before sending a request const { loading = true } = config; ("config:", config); // = vm.$("vue_admin_token"); if (loading) addLoading(); return config; }, function (error) { // What to do about the request error return (error); } ); // Add a response interceptor ( function (response) { // Do something about the response data ("response:", response); const { loading = true } = ; if (loading) cancelLoading(); const { code, data, message } = ; if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { (message); return (); } }, function (error) { // Do something to respond to errors ("error-response:", ); ("error-config:", ); ("error-request:", ); const { loading = true } = ; if (loading) cancelLoading(); if () { if ( === 401) { jumpLogin(); } } (error?.response?.data?.message || "Server side exception"); return (error); } ); return instance; };
Unified file download processing
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 = () => { // Increase loading If the number of pending requests is equal to 1, loading will be popped up to prevent repeated popups requestNum++; if (requestNum == 1) { loadingInstance = ({ text: "It's working hard to load...", background: "rgba(0, 0, 0, 0)", }); } }; const cancelLoading = () => { // Cancel loading If the number of pending requests is equal to 0, close loading requestNum--; if (requestNum === 0) loadingInstance?.close(); }; export const createAxiosByinterceptors = ( config?: AxiosRequestConfig ): AxiosInstance => { const instance = ({ timeout: 1000, //Timeout configuration withCredentials: true, //Carry cookies across domains ...config, // Custom configuration covers basic configuration }); // Add a request interceptor ( function (config: any) { // What to do before sending a request const { loading = true } = config; ("config:", config); // = vm.$("vue_admin_token"); if (loading) addLoading(); return config; }, function (error) { // What to do about the request error return (error); } ); // Add a response interceptor ( function (response) { // Do something about the response data ("response:", response); const { loading = true } = ; if (loading) cancelLoading(); const { code, data, message } = ; // config set responseType to blob to process file download if ( instanceof Blob) { return downloadFile(response); } else { if (code === 200) return data; else if (code === 401) { jumpLogin(); } else { (message); return (); } } }, function (error) { // Do something to respond to errors ("error-response:", ); ("error-config:", ); ("error-request:", ); const { loading = true } = ; if (loading) cancelLoading(); if () { if ( === 401) { jumpLogin(); } } (error?.response?.data?.message || "Server side exception"); return (error); } ); return instance; };
src/utils/ import { Message } from "element-ui"; import { AxiosResponse } from "axios"; import vm from "@/main"; /** * Jump login */ export const jumpLogin = () => { vm.$("vue_admin_token"); vm.$(`/login?redirect=${encodeURIComponent(vm.$)}`); }; /** * Download the file * @param response * @returns */ export const downloadFile = (response: AxiosResponse) => { (":", ); return new Promise((resolve, reject) => { const fileReader = new FileReader(); = function () { try { ("result:", ); const jsonData = ((this as any).result); // Success means it is normal object data if (jsonData?.code !== 200) { (jsonData?.message ?? "Request failed"); reject(jsonData); } } catch (err) { // Failed to parse into an object, indicating that it is a normal file stream const blob = new Blob([]); // Save file locally const url = (blob); const link = ("a"); = url; const filename = response?.headers?.["content-disposition"] ?.split("filename*=")?.[1] ?.substr(7); ("download", decodeURI(filename)); (link); (); resolve(); } }; (); }); };
use
import { createAxiosByinterceptors } from "@/api/request"; const request = createAxiosByinterceptors({ baseURL: localhost:7007, }); //lodaing configurationexport const appList = (params: any): Promise<any> => ("/app", { params, loading: true }); // You can configure loading to false to close loading.// File downloadexport const exportGoods = (data: any) => ("/export", data, { responseType: "blob", });
Finished scattering flowers😁😁😁
The above is the detailed content of the example of a useful axios step that saves time and effort in ten minutes. For more information about axios packaging steps, please pay attention to my other related articles!