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无尽的。

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver Mac版
视觉化网页开发工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。