uni.request封装

背景:

  在此项目基础上,后台需要增加token进行验证,token过期自动跳转到登录界面。由于前期项目搭建未考虑这种情况,现在需要对每个接口进行重新改造。于是将uni.request进行二次封装。也方便后期使用。

  1. 在common/js下创建一个request.js文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import store from '@/store/index'
const request = (options) => {
    return new Promise((resolve,reject) => {
        if(options.header) {
            options.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
        }else {
            let header = {'Authorization': 'Bearer ' + uni.getStorageSync('token')}
            options.header = header
        }
        console.log(JSON.stringify(options));
        uni.request({
            ...options,
            success: (res) => {
                console.log(res);
                if(res.data.status == '403') {
                    // 登录过期跳转到登录界面
                    uni.showToast({
                        title: '登录超时,请重新登录!',
                        icon: 'none'
                    });
                    // logOut()
                }
                if(res.data.status == '-1') {
                    uni.showToast({
                        title: res.data.msg ? res.data.msg : '接口请求失败!',
                        icon: 'none'
                    });
                }
                resolve(res)
            },
            fail: (err) => {
                console.log(err);
                console.log(options);
                reject(err)
            }
        })
    })
}
 
function logOut() {
    // let promise = this.tim.logout();
    // promise.then(res=> {
    const userNames = uni.getStorageSync('userName');
    const passwords = uni.getStorageSync('passWord');
    store.commit('isLogout');
    uni.clearStorage()
 
    uni.setStorageSync('userName', userNames);
    uni.setStorageSync('passWord', passwords);
    try{
        const jyJPush = uni.requireNativePlugin('JY-JPush');
        jyJPush.deleteJYJPushAlias(
            {
            },
            result => {
                console.log('删除别名:' + JSON.stringify(result));
                //删除别名后查看是否
                jyJPush.getJYJPushAlias(
                    {
                        userAlias: userNames + this.config.PUSH_KEY
                    },
                    result => {
                        console.log('删除别名后查看是否还有别名存在:' + JSON.stringify(result));
                    }
                );
            }
        );
    }catch(err){
        console.log(err)
    }
 
 
 
    uni.reLaunch({
        url: '../login/login'
    });
 
    // }).catch(err=> {
    //    console.log('退出失败')
    // });
}
export default request

  2. 在main.js中挂载到全局

  

import request from '@/common/js/request.js'
Vue.prototype.request = request

  3. 调用

复制代码
this.request({
    url: this.config.GET_LIST_WITH_GROUP + '?receiver=' + this.userData.id,
    methods: 'POST'
}).then((res) => {
    console.log(res)
    // TODO
},err => {
    uni.showToast({
        title: '请求失败',
        icon: 'none'
    });
})
复制代码

  注意:在main.js文件挂载后,在vue文件中可以直接使用this.request调用。但是在nvue文件中,需要在该文件中重新引用后再使用。

posted @   小韓烟柳  阅读(1386)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示