小程序request封装的详细流程

发布时间:2021-09-13 14:34:18 作者:chen
来源:亿速云 阅读:260

这篇文章主要讲解了“小程序request封装的详细流程”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“小程序request封装的详细流程”吧!

背景

之前小程序代码混乱,所以新项目一开始就准备弄个微信小程序的 request 的封装

流程

先来说说整个流程:

1.appjs 里面已进入就去获取用户信息,如果没有登录则默认登录,这里不做错误处理

2.用户必须同意授权才能进行操作,如果不同意授权则会一直跳转到授权页面

undefined

app.js

onLaunch 里面获取用户信息

appSelf = this;
        // 应用程序第一次进入,获取用户信息,不做任何错误处理
        userInfo().then( (res)=>{
            console.log(res);// 打印结果
            if (!res.code) {
                appSelf.globalData.userInfo = res
            }
        }).catch( (errMsg)=>{
            console.log(errMsg);// 错误提示信息
        });

httpUtils.js

request 的封装

const request = function (path, method, data, header) {
    let user_id = "";
    let token = "";
    try {
        user_id = wx.getStorageSync(USER_ID_KEY);
        token = wx.getStorageSync(TOKEN_KEY);
    } catch (e) {}
    header = header || {};
    let cookie = [];
    cookie.push("USERID=" + user_id);
    cookie.push("TOKEN=" + token);
    cookie.push("device=" + 1);
    cookie.push("app_name=" + 1);
    cookie.push("app_version=" + ENV_VERSION);
    cookie.push("channel=" + 1);
    header.cookie = cookie.join("; ");
    return new Promise((resolve, reject) => {
        wx.request({//后台请求
            url: API_BASE_URL + path,
            header: header,
            method: method,
            data: data,
            success: function (res) {
                if (res.statusCode !== 200) {
                    reject(res.data)
                } else {
                    if (res.data.code === 20006) {
                        login().then( (res)=>{
                            resolve(res)
                        }).catch( (errMsg)=>{
                            reject(errMsg);
                        })
                    }
                    resolve(res.data)
                }
            },
            fail: function (res) {
                reject("not data");
            }
        });
    });
}

login

const login = function () {
    try {
        wx.removeStorageSync(USER_ID_KEY)
        wx.removeStorageSync(TOKEN_KEY)
    } catch (e) {}
    return new Promise((resolve, reject) => {
        wx.login({
            success: res => {
                let code = res.code;
                // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
                wx.getUserInfo({
                    withCredentials: true,
                    success: res => {
                        let userInfo = res.userInfo;
                        let name = userInfo.nickName;
                        let avatar = userInfo.avatarUrl;
                        let sex = userInfo.gender;
                        let data = {
                            code: code,
                            encryptedData: res.encryptedData,
                            iv: res.iv,
                            name: name,
                            avatar: avatar,
                            sex: sex,
                            from: FROM,
                        };
                        request("/api/user/login/byWeChatApplet", "POST", data).then( (res)=>{
                            if (!res.code) {
                                try {
                                    wx.setStorageSync(USER_ID_KEY, res.user_id);
                                    wx.setStorageSync(TOKEN_KEY, res.token)
                                } catch (e) {
                                    reject(JSON.stringify(e));
                                }
                            }
                            resolve(res)
                        }).catch( (errMsg)=>{
                            reject(errMsg)
                        });
                    },
                    fail: function (res) {
                        console.log(res);

                        if (res.errMsg && res.errMsg.startsWith("getUserInfo:fail") && res.errMsg.search("unauthorized") != -1) {
                            // 跳转授权页面
                            wx.navigateTo({
                                url: '/pages/auth/auth'
                            })
                            return;
                        }
                        wx.getSetting({
                            success: (res) => {
                                if (!res.authSetting["scope.userInfo"]) {
                                    // 跳转授权页面
                                    wx.navigateTo({
                                        url: '/pages/auth/auth'
                                    })
                                }
                            }
                        });
                    }
                })
            }
        })
    });
};

auth.js

授权页面 js

Page({
    data: {
    },
    onLoad: function () {
        self = this;
    },

    auth: function (e) {
        console.log(app.globalData.userInfo);
        if (e.detail.userInfo) {
            login().then( (res)=>{
                console.log(res);// 打印结果
                if (res.code) {
                    // 接口错误
                    return
                }
                // 跳转回上一个页面
                wx.navigateBack()
            }).catch( (errMsg)=>{
                console.log(errMsg);// 错误提示信息
            });
        }
    },

});

感谢各位的阅读,以上就是“小程序request封装的详细流程”的内容了,经过本文的学习后,相信大家对小程序request封装的详细流程这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 怎么使用Promise封装小程序wx.request
  2. 微信小程序中wx.request如何实现封装

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

request

上一篇:Java中的深拷贝和浅拷贝是什么意思

下一篇:Redis集群收缩的概念和流程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》