From d1448cb0ef10f358bb7bddb4e1ec268515e0b787 Mon Sep 17 00:00:00 2001 From: gaoluyang <2820782392@qq.com> Date: 星期二, 15 七月 2025 11:46:57 +0800 Subject: [PATCH] 项目初始化 --- config/http.interceptor.js | 81 ++++++++++++++++++++++++++++++++++++++++ 1 files changed, 81 insertions(+), 0 deletions(-) diff --git a/config/http.interceptor.js b/config/http.interceptor.js new file mode 100644 index 0000000..e66995f --- /dev/null +++ b/config/http.interceptor.js @@ -0,0 +1,81 @@ +const { environment } = require('./environment.js') +import { ACCESS_TOKEN } from '@/store/mutation-types' +import storage from '@/utils/storage'; + +// 姝m鍙傛暟涓洪〉闈㈢殑瀹炰緥锛屽彲浠ラ�氳繃瀹冨紩鐢╲uex涓殑鍙橀噺 +module.exports = (vm) => { + // 鍒濆鍖栬姹傞厤缃� + uni.$u.http.setConfig((config) => { + /* config 涓洪粯璁ゅ叏灞�閰嶇疆锛岃姹傚湴鍧�鍒ゆ柇*/ + /* #ifdef H5 */ + if (process.env.NODE_ENV === 'production') { + config.baseURL = environment.baseURL; /* 鏍瑰煙鍚� */ + } else { + // 寮�鍙戞ā寮忓垯浣跨敤浠g悊鏂瑰紡锛岃vue.config.js閰嶇疆 + config.baseURL = '/'; /* 鏍瑰煙鍚� */ + } + /* #endif */ + /* #ifndef H5 */ + config.baseURL = environment.baseURL; /* 鏍瑰煙鍚� */ + /* #endif */ + return config + }) + + // 璇锋眰鎷︽埅 + uni.$u.http.interceptors.request.use((config) => { // 鍙娇鐢╝sync await 鍋氬紓姝ユ搷浣� + // 鍒濆鍖栬姹傛嫤鎴櫒鏃讹紝浼氭墽琛屾鏂规硶锛屾鏃禿ata涓簎ndefined锛岃祴浜堥粯璁} + config.data = config.data || {} + // 鏍规嵁custom鍙傛暟涓厤缃殑鏄惁闇�瑕乼oken锛屾坊鍔犲搴旂殑璇锋眰澶� + if(config?.custom?.auth) { + // 鍙互鍦ㄦ閫氳繃vm寮曠敤vuex涓殑鍙橀噺锛屽叿浣撳�煎湪vm.$store.state涓� + config.header.Authorization = 'Bearer ' + storage.get(ACCESS_TOKEN) + } + // 鏍规嵁custom鍙傛暟涓厤缃殑鏄惁闇�瑕佹樉绀簂oading + if (config?.custom?.loading) { + uni.showLoading({ + title: '鍔犺浇涓�...', + mask: true + }) + } + return config + }, config => { // 鍙娇鐢╝sync await 鍋氬紓姝ユ搷浣� + return Promise.reject(config) + }) + + // 鍝嶅簲鎷︽埅 + uni.$u.http.interceptors.response.use((response) => { /* 瀵瑰搷搴旀垚鍔熷仛鐐逛粈涔� 鍙娇鐢╝sync await 鍋氬紓姝ユ搷浣�*/ + const data = response.data + + // 鍏抽棴loading + uni.hideLoading(); + + // 鑷畾涔夊弬鏁� + const custom = response.config?.custom + if (data.code !== 200) { + // 濡傛灉娌℃湁鏄惧紡瀹氫箟custom鐨則oast鍙傛暟涓篺alse鐨勮瘽锛岄粯璁ゅ鎶ラ敊杩涜toast寮瑰嚭鎻愮ず + if (custom.toast !== false) { + uni.$u.toast(data.msg) + } + + // 鍒ゆ柇鐘舵�佺爜 + switch (data.code) { + case 401: { + uni.reLaunch({ url: '/' }) + return; + } + } + + // 濡傛灉闇�瑕乧atch杩斿洖锛屽垯杩涜reject + if (custom?.catch) { + return Promise.reject(data) + } else { + // 鍚﹀垯杩斿洖涓�涓猵ending涓殑promise锛岃姹備笉浼氳繘鍏atch涓� + return new Promise(() => { }) + } + } + return data === undefined ? {} : data + }, (response) => { + // 瀵瑰搷搴旈敊璇仛鐐逛粈涔� 锛坰tatusCode !== 200锛� + return Promise.reject(response) + }) +} \ No newline at end of file -- Gitblit v1.9.3