1. 程式人生 > >VUE的axios對Promise的封裝和攔截器

VUE的axios對Promise的封裝和攔截器

const prod = process.env.NODE_ENV !== "development"; const root = prod ? "/root" : "/root"; const timeout = 60000; import axios from "axios"; import * as types from "./interceptors"; import router from "router"; import { removeLocalStorage } from "./utils"; import { Message, Loading } from "element-ui";
/** * @method axiosGet get方法請求 * @method axiosPost get方法請求 * @method axiosPut get方法請求 * @method axiosDelete get方法請求 * @param {string} url url後臺路由地址 * @param {any} params 請求對接介面需要的資料 */ //建立axios例項 const createdAxiosInstance = config => { let instance, reqInterceptors, resInterceptors; if (config) { reqInterceptors = config.reqInterceptors; resInterceptors = config.resInterceptors; if (reqInterceptors || resInterceptors) { instance = axios.create(); } else { instance = axios; } if (reqInterceptors) { types.interceptorsRequest(instance); } if (resInterceptors) { types.interceptorsResponse(instance, config.exportFile); } } else { instance = axios; } return instance; };
function redirectLogin() { removeLocalStorage("smoke_session_token"); vueInstance.$store.commit("RESET_STATE"); router.replace({ path: "/login", query: { redirect: router.currentRoute.fullPath } }); Message.error({ message: "登入已失效,請重新登入!" }); if (window.stompClient) { window.stompClient.disconnect(); delete window.stompClient; } }
/** * @method axiosGet GET方法請求 * @param {*} url 請求地址 * @param {*} params 請求引數 * @param {*} config 配置 */ export const axiosGet = (url, params, config) => { const instance = createdAxiosInstance(config); const loadingFlag = config.loading === undefined ? true : config.loading; let loadingInstance; loadingInstance = loadingFlag ? Loading.service({ fullscreen: true, text: "拼命載入中", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.8)" }) : null; return new Promise(resolve => { instance({ method: "GET", url: url, params: params, baseURL: root, withCredentials: true, timeout: timeout, responseType: config.responseType }) .then(res => { loadingFlag ? loadingInstance.close() : null; if (res.resultCode !== 11000) { resolve(res); } else { redirectLogin(); } }) .catch(() => { loadingFlag ? loadingInstance.close() : null; }); }); };
/** * @method axiosPost POST方法請求 * @param {*} url 請求地址 * @param {*} params 請求引數 * @param {*} config 配置 */ export const axiosPost = (url, params, config) => { const instance = createdAxiosInstance(config); const loadingFlag = config.loading === undefined ? true : config.loading; let loadingInstance; loadingInstance = loadingFlag ? Loading.service({ fullscreen: true, text: "拼命載入中", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.8)" }) : null; return new Promise(resolve => { instance({ method: "POST", url: url, data: params, baseURL: root, timeout: timeout // withCredentials: true }) .then(res => { loadingFlag ? loadingInstance.close() : null; if (res.resultCode !== 11000) { resolve(res); } else { redirectLogin(); } }) .catch(() => { loadingFlag ? loadingInstance.close() : null; }); }); };
/** * @method axiosPut PUT方法請求 * @param {*} url 請求地址 * @param {*} params 請求引數 * @param {*} config 配置 */ export const axiosPut = (url, params, config) => { const instance = createdAxiosInstance(config); const loadingFlag = config.loading === undefined ? true : config.loading; let loadingInstance; loadingInstance = loadingFlag ? Loading.service({ fullscreen: true, text: "拼命載入中", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.8)" }) : null; return new Promise(resolve => { instance({ method: "PUT", url: url, data: params, baseURL: root, withCredentials: true, timeout: timeout }) .then(res => { loadingFlag ? loadingInstance.close() : null; if (res.resultCode !== 11000) { resolve(res); } else { redirectLogin(); } }) .catch(() => { loadingFlag ? loadingInstance.close() : null; }); }); };
/** * @method axiosDelete DELETE方法請求 * @param {*} url 請求地址 * @param {*} params 請求引數 * @param {*} config 配置 */ export const axiosDelete = (url, params, config) => { const instance = createdAxiosInstance(config); const loadingFlag = config.loading === undefined ? true : config.loading; let loadingInstance; loadingInstance = loadingFlag ? Loading.service({ fullscreen: true, text: "拼命載入中", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.8)" }) : null; return new Promise(resolve => { instance({ method: "DELETE", url: url, params: params, baseURL: root, withCredentials: true, timeout: timeout }) .then(res => { loadingFlag ? loadingInstance.close() : null; if (res.resultCode !== 11000) { resolve(res); } else { redirectLogin(); } }) .catch(() => { loadingFlag ? loadingInstance.close() : null; }); }); };     攔截器: import { setLocalStorage, removeLocalStorage, getLocalStorage } from "./utils"; import { Message } from "element-ui";
/** * @method interceptorsRequest http request 攔截器 * @param {Object} instance axios例項 * @param {Function} handle 攔截器操作函式 */ export const interceptorsRequest = instance => { // http request 攔截器 instance.interceptors.request.use( config => { const handle = () => { // 判斷是否存在token,如果存在的話,則每個http header都加上token const s_session = getLocalStorage("smoke_session_token"); if (s_session) { return s_session; } return null; }; config.headers.token = handle(); return config; }, err => { return Promise.reject(err); } ); };
/** * @method interceptorsRequest //http response 攔截器 * @param {Object} instance axios例項 * @param {Function} handle 攔截器操作函式 */ export const interceptorsResponse = (instance, exportFile) => { //http response 攔截器 instance.interceptors.response.use( response => { //對於檔案下載 if (exportFile) { if (response.data.type === "application/json") { //閉包把值傳出去,通過型別分辨blob和json return () => { return response.data; }; } else { return response.data; } } const session_token = response.headers.token; if (session_token) { setLocalStorage("smoke_session_token", session_token); } return response.data; }, error => { if (error.response) { const handle = error => { switch (error.response.status) { case 404: Message.error({ message: "請求資源不存在!" }); break; case 500: Message.error({ message: "伺服器內部有異常!" }); break; default: Message.error({ message: "伺服器內部異常!" }); break; } }; handle(error); } else { Message.error({ message: "請求資源超時!" }); } } ); };