實現的功能
用法及封裝
用法
// 服務層 , import默認會找該目錄下index.js的文件,這個可能有小伙伴不知道// 可以去了解npm的引入和es6引入的理論概念import axiosPlugin from "./server"; Vue.use(axiosPlugin);對axios的封裝(AXIOS: index.js )import axios from "axios";import qs from "qs";import { Message } from "element-ui";import router from "../router";const Axios = axios.create({ baseURL: "/", // 因為我本地做了反向代理 timeout: 10000, responseType: "json", withCredentials: true, // 是否允許帶cookie這些 headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" }});//POST傳參序列化(添加請求攔截器)Axios.interceptors.request.use( config => { // 在發送請求之前做某件事 if ( config.method === "post" ) { // 序列化 config.data = qs.stringify(config.data); // 溫馨提示,若是貴公司的提交能直接接受json 格式,可以不用 qs 來序列化的 } // 若是有做鑒權token , 就給頭部帶上token // 若是需要跨站點,存放到 cookie 會好一點,限制也沒那么多,有些瀏覽環境限制了 localstorage 的使用 // 這里localStorage一般是請求成功后我們自行寫入到本地的,因為你放在vuex刷新就沒了 // 一些必要的數據寫入本地,優先從本地讀取 if (localStorage.token) { config.headers.Authorization = localStorage.token; } return config; }, error => { // error 的回調信息,看貴公司的定義 Message({ // 餓了么的消息彈窗組件,類似toast showClose: true, message: error && error.data.error.message, type: 'error' }); return Promise.reject(error.data.error.message); });//返回狀態判斷(添加響應攔截器)Axios.interceptors.response.use( res => { //對響應數據做些事 if (res.data && !res.data.success) { Message({ // 餓了么的消息彈窗組件,類似toast showClose: true, message: res.data.error.message.message ? res.data.error.message.message : res.data.error.message, type: "error" }); return Promise.reject(res.data.error.message); } return res; }, error => { // 用戶登錄的時候會拿到一個基礎信息,比如用戶名,token,過期時間戳 // 直接丟localStorage或者sessionStorage if (!window.localStorage.getItem("loginUserBaseInfo")) { // 若是接口訪問的時候沒有發現有鑒權的基礎信息,直接返回登錄頁 router.push({ path: "/login" }); } else { // 若是有基礎信息的情況下,判斷時間戳和當前的時間,若是當前的時間大于服務器過期的時間 // 乖乖的返回去登錄頁重新登錄 let lifeTime = JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime * 1000; let nowTime = new Date().getTime(); // 當前時間的時間戳 console.log(nowTime, lifeTime); console.log(nowTime > lifeTime); if (nowTime > lifeTime) { Message({ showClose: true, message: "登錄狀態信息過期,請重新登錄", type: "error" }); router.push({ path: "/login" }); } else { // 下面是接口回調的satus ,因為我做了一些錯誤頁面,所以都會指向對應的報錯頁面 if (error.response.status === 403) { router.push({ path: "/error/403" }); } if (error.response.status === 500) { router.push({ path: "/error/500" }); } if (error.response.status === 502) { router.push({ path: "/error/502" }); } if (error.response.status === 404) { router.push({ path: "/error/404" }); } } } // 返回 response 里的錯誤信息 let errorInfo = error.data.error ? error.data.error.message : error.data; return Promise.reject(errorInfo); });// 對axios的實例重新封裝成一個plugin ,方便 Vue.use(xxxx)export default { install: function(Vue, Option) { Object.defineProperty(Vue.prototype, "$http", { value: Axios }); }};路由鉤子的調整(Router: index.js )
import Vue from "vue";import Router from "vue-router";import layout from "@/components/layout/layout";// 版塊有點多,版塊獨立路由管理,里面都是懶加載引入import customerManage from "./customerManage"; // 客戶管理import account from "./account"; //登錄import adManage from "./adManage"; // 廣告管理import dataStat from "./dataStat"; // 數據統計import logger from "./logger"; // 日志import manager from "./manager"; // 管理者import putonManage from "./putonManage"; // 投放管理import error from "./error"; // 服務端錯誤import { Message } from "element-ui";Vue.use(Router);// 請跳過這一段,看下面的const router = new Router({ hashbang: false, mode: "history", routes: [ { path: "/", redirect: "/adver", component: layout, children: [ ...customerManage, ...adManage, ...dataStat, ...putonManage, ...manager, ...logger ] }, ...account, ...error ]});// 路由攔截// 差點忘了說明,不是所有版塊都需要鑒權的// 所以需要鑒權,我都會在路由meta添加添加一個字段requireLogin,設置為true的時候// 這貨就必須走鑒權,像登錄頁這些不要,是可以直接訪問的!!!router.beforeEach((to, from, next) => { if (to.matched.some(res => res.meta.requireLogin)) { // 判斷是否需要登錄權限 if (window.localStorage.getItem("loginUserBaseInfo")) { // 判斷是否登錄 let lifeTime = JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime * 1000; let nowTime = (new Date()).getTime(); // 當前時間的時間戳 if (nowTime < lifeTime) { next(); } else { Message({ showClose: true, message: "登錄狀態信息過期,請重新登錄", type: "error" }); next({ path: "/login" }); } } else { // 沒登錄則跳轉到登錄界面 next({ path: "/login" }); } } else { next(); }});export default router;axios可配置的一些選項,其他的具體看官網說明哈
export default { // 請求地址 url: "/user", // 請求類型 method: "get", // 請根路徑 baseURL: "http://www.mt.com/api", // 請求前的數據處理 transformRequest: [function(data) {}], // 請求后的數據處理 transformResponse: [function(data) {}], // 自定義的請求頭 headers: { "x-Requested-With": "XMLHttpRequest" }, // URL查詢對象 params: { id: 12 }, // 查詢對象序列化函數 paramsSerializer: function(params) {}, // request body data: { key: "aa" }, // 超時設置s timeout: 1000, // 跨域是否帶Token withCredentials: false, // 自定義請求處理 adapter: function(resolve, reject, config) {}, // 身份驗證信息 auth: { uname: "", pwd: "12" }, // 響應的數據格式 json / blob /document /arraybuffer / text / stream responseType: "json", // xsrf 設置 xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", // 下傳和下載進度回調 onUploadProgress: function(progressEvent) { Math.round(progressEvent.loaded * 100 / progressEvent.total); }, onDownloadProgress: function(progressEvent) {}, // 最多轉發數,用于node.js maxRedirects: 5, // 最大響應數據大小 maxContentLength: 2000, // 自定義錯誤狀態碼范圍 validateStatus: function(status) { return status >= 200 && status < 300; }, // 用于node.js httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 用于設置跨域請求代理 proxy: { host: "127.0.0.1", port: 8080, auth: { username: "aa", password: "2123" } }, // 用于取消請求 cancelToken: new CancelToken(function(cancel) {})};總結
這個封裝雖說不是萬金油版本,但是我感覺大多用axios結合vue的小伙伴,稍微改改都能直接拿來用
鑒權需要再嚴謹一些,比如token 可以遵循 JWT 的規格,以及引入中間層nodejs(對傳輸的做攔截封裝加解密,聚合接口);
以上所述是小編給大家介紹的Vue中axios的封裝(報錯、鑒權、跳轉、攔截、提示),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答