uniapp请求封装 | 青训营笔记

294 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的第3天

前言

在写uniapp小程序项目过程中,没有使用云服务的情况下,有时候接口数量还是挺多的,而且有时候同一个接口可能多个地方都要调用,这时候一个基本可以满足所有情况下的请求api就显得很重要了

一个好的function可以减少很多重复的代码,也易于代码的检查和修改,但在越后期,每一次的修改都得考虑兼容现在调用该方法的场景,所以提前考虑好多种可能情况下封装一个请求最好啦

废话不多说,直接上思路

项目背景

1.小程序框架:uniapp

2.框架语法:vue3

3.编辑工具:vscode

4.涉及api:uni.request

5.需求:封装一个适用多场景的请求api

具体实现

参考uni.request

image.png

let baseUrl = 'http://xxxx';//服务器地址
let methods = ['get', 'post','delete'];//涉及到的请求method
import updateUserInfo  from "./updateUserInfo";
export default function request(url, data, methodIndex) {
    let header = {
        'content-type': 'application/json',
    }
    let token = uni.getStorageSync('token');//从本地存储中获取token,存在则添加到请求投中
    if (token !== '') {
        header['Authorization'] = token
    }
    //利用promise实现请求
    return new Promise((resolve, reject) => {
        uni.request({
            header,
            url: baseUrl + url,
            method: methods[methodIndex],
            data,
            success: res => {
                if (res.data.code == 200) {
                //正常请求且正常返回数据的情况下
                    resolve(res.data.data)
                } else if (res.data.code == 4005) {
                //用户token过期或不存在的情况下
                //还涉及到token过期情况下小程序端自动更新token
                    updateUserInfo().then(() => {
                        uni.showToast({
                            title: '请重试',
                            icon:'error'
                        })
                    }).catch(() => {
                        
                    })
                } else {
                    uni.showToast({
                        title: '请求错误',
                        icon: 'error'
                    })
                    //请求失败时返回url,这里是方便测试的时候用的
                    reject({url})
                }
            },
            fail: reason => {
                reject({url})
            }
        })
    })
}

image.png

export default function updateUserInfo() {
    return new Promise((resolve, reject) => {
        uni.login({
            success: (res) => {
                uni.request({
                    url: 'http://xxxxx/user/wechat/login',//后端人员写的微信登录接口
                    method: 'GET',
                    data: {
                        code:res.code
                    },
                    success: (response) => {
                        response = response.data.data
                        //重新更新token已经其他个人信息
                        uni.setStorage({
                            key: "user",
                            data: response.userProfile,
                        });
                        uni.setStorage({
                            key: "token",
                            data: response.accessToken,
                        });
                        uni.setStorage({
                            key: "expireTime",//这里是token过期时间戳还涉及token自动更新,相关api这里暂时没写
                            data: response.expireTime,
                        });
                        resolve()
                    },
                    fail: () => {
                        reject()
                    }
                })
            },
            fail: () => {
                reject()
            },
        });
    })
}