代做畢設(shè)的網(wǎng)站廣州網(wǎng)站優(yōu)化運營
1、axios官網(wǎng)
https://www.axios-http.cn/docs/interceptors?
2、安裝
npm install axios
3、在onMouunted鉤子函數(shù)中使用axios來發(fā)送請求,接受響應
?
4.出現(xiàn)的問題:
(1) 但是如果發(fā)送請求請求時間過長,回出現(xiàn)請求待處理的情況,用戶體驗很不好,沒有畫面,我們可以加一個loding遮罩層,提示用戶正在加載中,但是如果沒個請求都手動添加,代碼冗余
?
(2) 每個請求都要考慮,程序報錯的情況,都需要catch一下,處理下異常,而且在拿數(shù)據(jù)時我們后端寫了統(tǒng)一返回格式,但是前端響應的數(shù)據(jù)res里我們的數(shù)據(jù)被一層一層包裹著,每次都要一層一層的拿,代碼冗余
?
5、解決方法:
?使用axios的攔截器
?新建一個http文件夾,新建index.ts文件用于定義請求和響應攔截器,在請求和響應攔截器中解決以上問題
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
const config = {baseURL: '',timeout: 30 * 1000,withCredentials: true,
}let loading: any
class Http {myAxios: any;constructor(config: any) {this.myAxios = axios.create(config);// 添加請求攔截器this.myAxios.interceptors.request.use(function (config: any) {//在發(fā)送請求時加載loading層loading = ElLoading.service({lock: true,text: '加載中...',background: 'rgba(0, 0, 0, 0.7)',})return config;}, function (error: any) {// 對請求錯誤做些什么loading.close()return Promise.reject(error);});// 添加響應攔截器this.myAxios.interceptors.response.use(function (response: any) {//在響應后關(guān)閉loading層loading.close()//取出響應的數(shù)據(jù)進行判斷const { code, message, data } = response.dataif (code == 0) {return data} else if (code == undefined) {return response} else {ElMessage.error(message)return Promise.reject(message);}}, function (error: any) {loading.close()return Promise.reject(error);});}get<T>(url: string, params?: object, data = {}): Promise<any> {return this.myAxios.get(url, { params, ...data });}post<T>(url: string, params?: object, data = {}): Promise<any> {return this.myAxios.post(url, params, data);}put<T>(url: string, params?: object, data = {}): Promise<any> {return this.myAxios.put(url, params, data);}delete<T>(url: string, params?: object, data = {}): Promise<any> {return this.myAxios.delete(url, { params, ...data });}}export default new Http(config);
在頁面中使用時,直接使用用axios封裝好的類
?
結(jié)果:
?
?
?
?
?
?
?