首頁 >微信小程式 >小程式開發 >關於小程式的request封裝(附詳細流程)

關於小程式的request封裝(附詳細流程)

藏色散人
藏色散人轉載
2021-09-11 17:07:193631瀏覽

背景

之前小程式碼混亂,所以新專案一開始就準備弄個微信小程式的request 的封裝

#流程

先來說說整個流程:

1.appjs 裡面已進入就去獲取使用者訊息,如果沒有登入則預設登錄,這裡不做錯誤處理

2.使用者必須同意授權才能進行操作,如果不同意授權則會一直跳到授權頁面

3.在授權頁面點擊授權登入後,調用登入接口,成功後返回調起授權的頁面,

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);// 错误提示信息
            });
        }
    },

});

專案位址

#https://github.com/lmxdawn/wx...

一個vue thinkphp5.1 搭建的後台管理:https://github.com/lmxdawn/vu...

示範:<br>關於小程式的request封裝(附詳細流程)

##
<br>

以上是關於小程式的request封裝(附詳細流程)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除