0

0

uniapp如何添加请求拦截器

coldplay.xixi

coldplay.xixi

发布时间:2021-02-01 17:01:20

|

9935人浏览过

|

来源于php中文网

原创

uniapp添加请求拦截器的方法:1、定义LsxmRequest类并添加默认配置、拦截器与请求方法;2、后续需要自定义config与获取接口地址,在类中添加get和set方法;3、利用Symbol特性定义四个私有变量,防止变量污染。

uniapp如何添加请求拦截器

本教程操作环境: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生命周期混入。

万彩商图
万彩商图

专为电商打造的AI商拍工具,快速生成多样化的高质量商品图和模特图,助力商家节省成本,解决素材生产难、产图速度慢、场地设备拍摄等问题。

下载
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栏目~

相关专题

更多
Word 字间距调整方法汇总
Word 字间距调整方法汇总

本专题整合了Word字间距调整方法,阅读下面的文章了解更详细操作。

2

2025.12.24

任务管理器教程
任务管理器教程

本专题整合了任务管理器相关教程,阅读下面的文章了解更多详细操作。

2

2025.12.24

AppleID格式
AppleID格式

本专题整合了AppleID相关内容,阅读专题下面的文章了解更多详细教程。

0

2025.12.24

csgo视频观看入口合集
csgo视频观看入口合集

本专题整合了csgo观看入口合集,阅读下面的文章了知道更多入口地址。

29

2025.12.24

yandex外贸入口合集
yandex外贸入口合集

本专题汇总了yandex外贸入口地址,阅读下面的文章了解更多内容。

58

2025.12.24

添加脚注通用方法
添加脚注通用方法

本专题整合了添加脚注方法合集,阅读专题下面的文章了解更多内容。

1

2025.12.24

重启电脑教程汇总
重启电脑教程汇总

本专题整合了重启电脑操作教程,阅读下面的文章了解更多详细教程。

3

2025.12.24

纸张尺寸汇总
纸张尺寸汇总

本专题整合了纸张尺寸相关内容,阅读专题下面的文章了解更多内容。

5

2025.12.24

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

1

2025.12.24

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号