時隔一年再次更新下根據vue項目下常見業務場景對axios的二次封裝
功能實現:
1.兼容ie瀏覽器避免緩存
2.減小或更新重複請求
3.接口域名使用環境變量
4.全局loading狀態
5.可關閉的全局錯誤提醒
6.可開啓攜帶全局分頁參數
7...前端
/** * 請求攔截器 * @param {} requestStart 請求開始 */ service.interceptors.request.use( config => { requestStart({ config }); return config; }, error => { Message.error("請求出錯"); Promise.reject(error); } ); /** * 響應攔截器 * @param {} requestEnd 1.請求結束 * @param {} responseResolve 2.請求錯誤處理 */ service.interceptors.response.use( response => { const { status, data, config } = response; requestEnd({ config, data }); return responseResolve({ status, data, config }); }, error => { if (axios.isCancel(error)) { Message.warning("網絡請求中,請不要重複操做!"); } else { const { response } = error; Message.error({ dangerouslyUseHTMLString: true, message: `<p>請求接口: ${ response.config.url }</p><p>請求方法 : ${ response.config.method }</p><p>響應狀態 : ${response.status}</p><p>響應信息 : ${ response.statusText }</p>` }); } store.commit("setLoading", false); store.commit("setPageTotal", 0); return Promise.reject(error); } );
/** * 請求開始&&loading=true * @param {} requestHeaders 請求頭 * @param {} requestParams 請求參數 * @param {} removePending 重複請求 */ const requestStart = ({ config } = {}) => { requestHeaders({ config }); requestParams({ config }); removePending({ config }); addPending({ config }); store.commit("setLoading", true); };
/** * @param {} {status HTTP狀態碼 * @param {} data 響應體 * @param {} config}={} AxiosRequestConfig */ const responseResolve = ({ status, data, config } = {}) => { const { code, text } = data; if (status === 200) { switch (code) { case 200: return Promise.resolve(data); case 900401: Message.error(text || "登陸超時,請從新登陸!"); window.location.href = process.env.VUE_APP_AUTH_URL; return Promise.reject(data); default: //可配置錯誤提醒 if (!config.headers["hide-message"]) { Message.error(text || "操做失敗!"); } return Promise.reject(data); } } else { Message.error(text || "操做失敗!"); store.commit("setLoading", false); return Promise.reject(data); } };
/** * 請求結束&&loading=false * @param {} {config}={} AxiosRequestConfig * @param {} {config}={} response body */ const requestEnd = ({ config, data } = {}) => { removePending({ config }); store.commit("setLoading", false); //配置分頁 if (config.headers.pagination) { const { data: content } = data; if (content) { store.commit("setPageTotal", content.total); } } };
/** * 請求頭預處理 * @param {} {config} AxiosRequestConfig */ const requestHeaders = ({ config }) => { //1.時間戳 const timestamp = new Date().getTime(); config.headers.timestamp = timestamp; //2.token const token = sessionStorage.getItem("token"); if (token) { config.headers.token = token; } };
/** * 請求參數預處理 * @param {} {config}={} AxiosRequestConfig */ const requestParams = ({ config } = {}) => { //配置分頁 if (config.headers.pagination) { const { pageNum, pageSize } = store.getters.getPagination; config.data = Object.assign({}, config.data, { pageNum, pageSize }); } };
/** * 處理重複請求 * @param {} {config}={} AxiosRequestConfig */ const addPending = ({ config }) => { const url = config.url + "&" + config.method + "&" + qs.stringify(config.data); config.cancelToken = new cancelToken(cancel => { if (!pending.some(item => item.url === url)) { pending.push({ url, cancel }); } }); }; const removePending = ({ config }) => { const url = config.url + "&" + config.method + "&" + qs.stringify(config.data); pending.forEach((item, index) => { if (item.url === url) { item.cancel("取消重複請求:" + config.url); pending.splice(index, 1); } }); };
import { Message } from "element-ui"; import axios from "axios"; import store from "../store/index"; const qs = require("qs"); const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, timeout: 100000 }); const pending = []; const cancelToken = axios.CancelToken; /** * 處理重複請求 * @param {} {config}={} AxiosRequestConfig */ const addPending = ({ config }) => { const url = config.url + "&" + config.method + "&" + qs.stringify(config.data); config.cancelToken = new cancelToken(cancel => { if (!pending.some(item => item.url === url)) { pending.push({ url, cancel }); } }); }; const removePending = ({ config }) => { const url = config.url + "&" + config.method + "&" + qs.stringify(config.data); pending.forEach((item, index) => { if (item.url === url) { item.cancel("取消重複請求:" + config.url); pending.splice(index, 1); } }); }; /** * 請求頭預處理 * @param {} {config} AxiosRequestConfig */ const requestHeaders = ({ config }) => { //1.時間戳 const timestamp = new Date().getTime(); config.headers.timestamp = timestamp; //2.token const token = sessionStorage.getItem("token"); if (token) { config.headers.token = token; } }; /** * 請求參數預處理 * @param {} {config}={} AxiosRequestConfig */ const requestParams = ({ config } = {}) => { //配置分頁 if (config.headers.pagination) { const { pageNum, pageSize } = store.getters.getPagination; config.data = Object.assign({}, config.data, { pageNum, pageSize }); } }; /** * 請求開始&&loading=true * @param {} requestHeaders 1.配置請求頭 * @param {} requestParams 2.配置請求體 * @param {} removePending 3.處理重複請求 */ const requestStart = ({ config } = {}) => { requestHeaders({ config }); requestParams({ config }); removePending({ config }); addPending({ config }); store.commit("setLoading", true); }; /** * 請求結束&&loading=false * @param {} {config}={} AxiosRequestConfig * @param {} {config}={} response body */ const requestEnd = ({ config, data } = {}) => { removePending({ config }); store.commit("setLoading", false); //配置分頁 if (config.headers.pagination) { const { data: content } = data; if (content) { store.commit("setPageTotal", content.total); } } }; /** * @param {} {status HTTP狀態碼 * @param {} data 響應體 * @param {} config}={} AxiosRequestConfig */ const responseResolve = ({ status, data, config } = {}) => { const { code, text } = data; if (status === 200) { switch (code) { case 200: return Promise.resolve(data); case 900401: Message.error(text || "登陸超時,請從新登陸!"); window.location.href = process.env.VUE_APP_AUTH_URL; return Promise.reject(data); default: //可配置錯誤提醒 if (!config.headers["hide-message"]) { Message.error(text || "操做失敗!"); } return Promise.reject(data); } } else { Message.error(text || "操做失敗!"); store.commit("setLoading", false); return Promise.reject(data); } }; /** * 請求攔截器 * @param {} requestStart 請求開始 */ service.interceptors.request.use( config => { requestStart({ config }); return config; }, error => { Message.error("請求出錯"); Promise.reject(error); } ); /** * 響應攔截器 * @param {} requestEnd 1.請求結束 * @param {} responseResolve 2.請求錯誤處理 */ service.interceptors.response.use( response => { const { status, data, config } = response; requestEnd({ config, data }); return responseResolve({ status, data, config }); }, error => { if (axios.isCancel(error)) { Message.warning("網絡請求中,請不要重複操做!"); } else { const { response } = error; Message.error({ dangerouslyUseHTMLString: true, message: `<p>請求接口: ${ response.config.url }</p><p>請求方法 : ${ response.config.method }</p><p>響應狀態 : ${response.status}</p><p>響應信息 : ${ response.statusText }</p>` }); } store.commit("setLoading", false); store.commit("setPageTotal", 0); return Promise.reject(error); } ); export default service;