結合axios對專案中的api請求進行封裝
阿新 • • 發佈:2020-08-19
原文地址:https://www.cnblogs.com/yalong/p/13531223.html
痛點:
1. 後端對全部請求的url進行了調整。 2.後端要求給所有的請求頭部新增一個token, 或者對請求新增其他全域性處理。 3.請求程式碼直接寫在每個頁面裡, 看起來程式碼臃腫,不夠簡練,太難管理。 4.看到請求程式碼, 不明白該請求是幹嘛的,語義化不夠明顯。 ...上面列舉的是一些常見的問題,如果沒對api進行封裝,當請求比較多的時候,修改起來欲哭無淚,解決這些問題可以進行以下操作
1.對axios進行二次封裝 2.對全部api請求也進行封裝如下是對axios 進行二次封裝, 檔名是 network/index.js:
import axios from "axios"; import Cookies from "js-cookie"; // 設定超時時間 const myAxios = axios.create({ timeout: 5000 }); // 跳轉登入頁面 function nav2Login() { location.href = '/xxxx/login' } // 新增一個請求攔截器 myAxios.interceptors.request.use( function(config) { // Do something before request is sent
config.headers["token"] = Cookies.get("token") || ""; return config; }, function(error) { // Do something with request error return Promise.reject(error); } ); // 新增一個響應攔截器 myAxios.interceptors.response.use( function(response) { // Do something with response data // 這裡只是以200 401為示例, 其他狀態碼可以根據需要自行新增if (response.status === 200) { return response.data; } else if (response.status === 401) { nav2Login() return Promise.reject(); } else { return { status: 0, message: response.data.message }; } }, function(error) { // Do something with response error return Promise.reject(error); } ); export default myAxios;
下面是對全部的api進行了封裝,檔名是 network/api.js:
import axios from "./index.js"; const API = { userList: 'api/user/all', // 使用者列表 cityList: 'api/city/all', // 城市列表 }; function Axios(obj) { return axios({ ...obj }).catch(e => { // 這裡兜住error, 從而不影響後續程式碼執行,避免出現白屏 return { status: 0, message: "網路請求異常" }; }); } // 給函式命名的時候 儘量語義化 function getUserList(params) { return Axios({ url: API.userList, method: "post", params }); } function getCityList(params) { return Axios({ url: API.cityList, method: "get", params }); } export default { getUserList, getCityList, }
可以把這些請求掛載在一個全域性的變數上, 以Vue為例:
import Vue from 'vue' import App from './App.vue' import router from './router' import api from "@/network/api.js"; Vue.prototype.$api = api; new Vue({ router, render: h => h(App) }).$mount('#app')
Vue專案中使用方法如下:
this.$api.getUserList(obj).then(res => { // 處理res }).catch(err){ // 處理 err } // 或者使用async await async getUserList () { try { const res = await this.$api.getUserList(obj) // 處理res } catch (err) { // 處理err } }