uniapp新增請求攔截器的方法:1、定義LsxmRequest類別並新增預設設定、攔截器與請求方法;2、後續需要自訂config與取得介面位址,在類別中新增get和set方法;3.利用Symbol特性定義四個私有變量,防止變量污染。
本教學操作環境:windows7系統、uni-app2.5.1版本,DELL G3電腦,此方法適用於所有品牌電腦。
uniapp加入請求攔截器的方法:
1、利用Symbol特性定義四個私有變量,防止變數污染
const config = Symbol('config') const isCompleteURL = Symbol('isCompleteURL') const requestBefore = Symbol('requestBefore') const requestAfter = Symbol('requestAfter')
2、定義LsxmRequest類別並新增預設設定、攔截器與請求方法
class LsxmRequest { //默认配置 [config] = { baseURL: '', header: { 'content-type': 'application/json' }, method: 'GET', dataType: 'json', responseType: 'text' } //拦截器 interceptors = { request: (func) => { if (func) { LsxmRequest[requestBefore] = func } else { LsxmRequest[requestBefore] = (request) => request } }, response: (func) => { if (func) { LsxmRequest[requestAfter] = func } else { LsxmRequest[requestAfter] = (response) => response } } } static [requestBefore] (config) { return config } static [requestAfter] (response) { return response } static [isCompleteURL] (url) { return /(http|https):\/\/([\w.]+\/?)\S*/.test(url) } request (options = {}) { options.baseURL = options.baseURL || this[config].baseURL options.dataType = options.dataType || this[config].dataType options.url = LsxmRequest[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url) options.data = options.data options.header = {...options.header, ...this[config].header} options.method = options.method || this[config].method options = {...options, ...LsxmRequest[requestBefore](options)} return new Promise((resolve, reject) => { options.success = function (res) { resolve(LsxmRequest[requestAfter](res)) } options.fail= function (err) { reject(LsxmRequest[requestAfter](err)) } uni.request(options) }) } get (url, data, options = {}) { options.url = url options.data = data options.method = 'GET' return this.request(options) } post (url, data, options = {}) { options.url = url options.data = data options.method = 'POST' return this.request(options) } }
3、後續需要自訂config與取得介面位址,在類別中加入get與set方法:
setConfig (func) { this[config] = func(this[config]) } getConfig() { return this[config]; }
4、用自訂外掛程式註冊的方法將apis.js(後續在main.js中需要導入apis.js)中的介面賦到自訂的Vue原型變數$lsxmApi上,為了避免每個頁面都要引入一次,在每個頁面的beforeCreate生命週期混入。
LsxmRequest.install = function (Vue) { Vue.mixin({ beforeCreate: function () { if (this.$options.apis) { console.log(this.$options.apis) Vue._lsxmRequest = this.$options.apis } } }) Object.defineProperty(Vue.prototype, '$lsxmApi', { get: function () { return Vue._lsxmRequest.apis } }) } export default LsxmRequest
5、在config.js中實例化並自訂請求設定項目(此處根據專案需求在頭部加入token)與攔截器
import LsxmRequest from './LsxmRequest' const lsxmRequest = new LsxmRequest() // 请求拦截器 lsxmRequest.interceptors.request((request) => { if (uni.getStorageSync('token')) { request.header['token'] = uni.getStorageSync('token'); } return request }) // 响应拦截器 lsxmRequest.interceptors.response((response) => { console.log('beforeRespone',response); // 超时重新登录 if(response.data.isOverTime){ uni.showModal({ title:'提示', content:'您已超时,请重新登录!', showCancel:false, icon:'success', success:function(e){ if(e.confirm){ uni.redirectTo({ url: '/pages/login/login' }) } } }); } else { return response; } }) // 设置默认配置 lsxmRequest.setConfig((config) => { config.baseURL = 'http://xxxxx.com' if (uni.getStorageSync('token')) { config.header['token'] = uni.getStorageSync('token'); } return config; }) export default lsxmRequest
6、main.js中引入,將apis掛載到Vue上
import LsxmRequest from './service/LsxmRequest.js' import apis from './service/apis.js' import lsxmRequest from './service/config.js' Vue.use(LsxmRequest) Vue.prototype.baseDomain = lsxmRequest.getConfig().baseURL App.mpType = 'app' const app = new Vue({ store, apis, ...App }) app.$mount()
7、需要新增介面時,只需在apis.js中新增介面即可(後續可將apis.js中的介面依照功能拆分,模組化管理)
import lsxmRequest from './config.js' export default{ apis:{ //获取验证用户令牌 getLoginToken(data){ return lsxmRequest.post('/xxx/xxx/getLoginToken', data) }, //登录 login(data){ return lsxmRequest.post('/xxx/xxx/login', data) } } }
8、至此,頁面中即可使用
this.$lsxmApi.getLoginToken({}).then((resToken) => { console.log(resToken) }
#了解更多其他精品文章,敬請關注uni-app欄~
以上是uniapp如何新增請求攔截器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了有關移動和網絡平台的調試策略,突出顯示了Android Studio,Xcode和Chrome DevTools等工具,以及在OS和性能優化的一致結果的技術。

文章討論了用於Uniapp開發的調試工具和最佳實踐,重點關注Hbuilderx,微信開發人員工具和Chrome DevTools等工具。

本文討論了跨多個平台的Uniapp應用程序的端到端測試。它涵蓋定義測試方案,選擇諸如Appium和Cypress之類的工具,設置環境,寫作和運行測試,分析結果以及集成

本文討論了針對Uniapp應用程序的各種測試類型,包括單元,集成,功能,UI/UX,性能,跨平台和安全測試。它還涵蓋了確保跨平台兼容性,並推薦Jes等工具

本文討論了UNIAPP開發中的共同績效抗模式,例如過度的全球數據使用和效率低下的數據綁定,並提供策略來識別和減輕這些問題,以提高應用程序性能。

本文討論了通過壓縮,響應式設計,懶惰加載,緩存和使用WebP格式來優化Uniapp中的圖像,以更好地進行Web性能。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)